I need to implement a function that takes as a parameter a list of names(strings) and another parameter that takes a list of characters. The function should print out the names in the first list that start with the letters in the second list. If the list is empty, the function doesnt print anythig.
here is how the function call would look like and its outputs
>>> selectSome(["Emma", "Santana", "Cam", "Trevor", "Olivia", "Arthur"], ['A', 'B', 'C', 'D', 'E', 'F'])
Emma
Cam
Arthur
>>> selectSome(["Holly", "Bowel", "champ", 'Fun', 'Apu'], ['a', 'F', 'C'])
champ
Fun
Apu
>>> selectSome([], ['a', 'b', 'c'])
>>> selectSome(['Eva', 'Bob'], [])
>>>
Here's the gist of what you need:
>>> names = ['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo', 'Foxtrot']
>>> first_letters = ['A','B','C']
>>> output_names = [name for name in names if (name[0] in first_letters)]
>>> output_names
['Alpha', 'Bravo', 'Charlie']
I'll leave wrapping that as a function up to you.
Test your understanding:
for
loop?Check Python's documentation for the "startswith" string method: http://docs.python.org/library/stdtypes.html#str.startswith
str.startswith(prefix[, start[, end]]) Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.
Changed in version 2.5: Accept tuples as prefix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With