获取字符串列表中的最后3个字母

时间:2017-10-03 01:50:05

标签: python string indexing slice

例如:

def get_last_three_letters(a_list):
    for name in a_list:
        name = name[-3:].lower()

    return name

def main():
   print("1.", get_last_three_letters(["Jess", "Cain", "Amity", "Raeann"]))
   print("2.", get_last_three_letters(["CAIn", "JessiE", "O", "ROBERT", 
   "Geoffrey", "Li", "B"]))
   print("3.", "***" + get_last_three_letters([]) + "***")
   print("4.", "***" + get_last_three_letters(["A", "E", "O"]) + "***")

我的输出如下:

 1. ann
 2. b

我试图从字符串中获取最后3个字符,我希望输出如下:

 1. essainityann
 2. ainsieertrey

我不知道如何修复它。

2 个答案:

答案 0 :(得分:2)

这里的问题是你在每次迭代时都覆盖names。相反,请保留一个列表, append 这些值,最后str.join然后返回。

def get_last_three_letters(a_list):
    tails = []
    for name in a_list:
        if len(name) > 2:
            tails.append(name[-3:].lower())

    return ''.join(tails)

您可以将其缩短为列表理解,如this answer所述。

def get_last_three_letters(a_list):
    return ''.join([x[-3:].lower() for x in a_list if len(x) > 2])

请注意,将列表传递给str.join实际上比生成器理解更快!

>>> get_last_three_letters(["Jess", "Cain", "Amity", "Raeann"])
'essainityann'
>>> get_last_three_letters(["CAIn", "JessiE", "O", "ROBERT", "Geoffrey", "Li", "B"])
'ainsieertrey'

答案 1 :(得分:2)

这应该足以做到这一点:

def get_last_three_chars(my_list):
    return ''.join(x[-3:].lower() for x in my_list if len(x) >= 3)
>>> get_last_three_chars(["Jess", "Cain", "Amity", "Raeann"])
'essainityann'
>>> get_last_three_chars(["CAIn", "JessiE", "O", "ROBERT", "Geoffrey", "Li", "B"])
'ainsieertrey'