Home > other >  Function that prints certain letters of a given string
Function that prints certain letters of a given string

Time:02-22

I am trying to make a 'def' function that takes a list of random strings, and a separate list of random numbers, and will return a list of all strings that end with one of the letters in the given letter list. Ex: function 'lastLetter' takes two parameters: 'str1', a list of random strings, and 'letters', a list of random letters, and returns all strings in 'str1' that end with a letter in 'letters'.

CodePudding user response:

You can use list comprehension, indexing, and in:

def has_final_letter(words, letters):
    letters = set(letters) # you can omit this
    return [word for word in words if word[-1] in letters]

str1 = ["Horse", "Cow", "Pig"]
letters = ["a", "b", "e"]

print(has_final_letter(str1, letters)) # ['Horse']

Of course this would result in an error if you have an empty string. To avoid that, you can insert word and between if and word[-1]:

[word for word in words if word and word[-1] in letters]

(Now reading out this sentence, full of word, feels a little funny lol.)

  • Related