[SOLVED] Function that prints certain letters of a given string

Issue

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’
.

Solution

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"] # or letters = 'abe'

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 words, feels a little funny lol.)


If you want a full for loop version:

def has_final_letter(words, letters):
    output = []
    for word in words:
        if word == '': # check if word is empty
            continue # skip this empty word
        for letter in letters:
            if word[-1] == letter:
                output.append(word)
    return output

Answered By – j1-lee

Answer Checked By – Marie Seifert (BugsFixing Admin)

Leave a Reply

Your email address will not be published.