Get a list of names which start with certain letters

20,924

Solution 1

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:

  1. how do you make this case-insensitive?
  2. Do you understand what line 3 does? (it's called a list comprehension.) Can you write the equivalent for loop?

Solution 2

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.

Share:
20,924
GelatinFox
Author by

GelatinFox

Updated on July 12, 2022

Comments

  • GelatinFox
    GelatinFox almost 2 years

    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'], [])
    >>>
    
  • Li-aung Yip
    Li-aung Yip about 12 years
    Natch, this was probably homework and I shouldn't have given this much of an answer. In future, you'll be expected to demonstrate that you've tried to solve your own problem ("what have you tried?") before you get this level of help.
  • Li-aung Yip
    Li-aung Yip about 12 years
    Ah, that is indeed a better solution. +1. (Coming from C and then MATLAB, I think of everything in terms of array indexing instead of "starts with".)
  • Marco smdm
    Marco smdm about 6 years
    That is a very good solution...just you have to read properly (Tuple)...so here the suggestion is to use a tuple as prefix! very good