Kee Kee - 3 years ago 172
Python Question

Get last three letters in a list of names

An example be like:

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"]) + "***")

my output like:

1. ann
2. b

I'm trying to get the last 3 characters from a string,I expect to get the output like:

1. essainityann
2. ainsieertrey

I don't know how to fix it.

Answer Source

The problem here is you're overwriting names at each iteration. Instead, keep a list, and append those values, and finally str.join them and return.

def get_last_three_letters(a_list):
    tails = []
    for name in a_list:
        if len(name) > 2:

    return ''.join(tails)

You can shorten this to a list comprehension, as this answer mentions.

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

Note that passing a list to str.join is actually faster than a generator comprehension!

>>> get_last_three_letters(["Jess", "Cain", "Amity", "Raeann"])
>>> get_last_three_letters(["CAIn", "JessiE", "O", "ROBERT", "Geoffrey", "Li", "B"])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download