Alec Cunningham
Alec Cunningham

Reputation: 813

Print strings in a list that begin with a specific character

Currently, I have this:

lst = ['Eleanor', 'Sammy', 'Owen', 'Gavin']

def partition(lst):
    if any('abcdefghijklm') in ([x[0] for x in lst]):
        print(lst)
    else:
        print('This still isn\'t working')

I am trying to examine the first character of each string in lst and only print the strings in lst that start with any letter A-M. I cannot seem to find any method that supports this. Is there any native method that I'm overlooking?

Upvotes: 0

Views: 923

Answers (3)

justanr
justanr

Reputation: 750

You're misunderstanding what any does. It returns True if any member of an iterable fed to it is True: print(any([False, [], 0, None, 'a'])) #outputs True Conversely, all only returns True if every member of an iterable passed to it is True.

It is a powerful tool, however, and you can use for this task:

from string import ascii_lowercase as lowercase #a-z

def partition(*names):
    if any(n[0].lower() in lowercase[:13] for n in names):
        print(*names)
    else:
        print("No names matched the criteria")

partition('Eleanor', 'Sammy', 'Owen', 'Gavin')

Upvotes: 1

Alfe
Alfe

Reputation: 59426

How about the plain and simple:

def partition(lst):
    print([ x for x in lst if x[0].lower() in 'abcdefghijklm' ])

Or what about the very clear:

def partition(lst):
    for word in lst:
        if word[0] in 'abcdefghijklm':
             print(word)

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113935

lst = ['Eleanor', 'Sammy', 'Owen', 'Gavin']
whitelist = set('abcdefghijklm')
for name in lst:
    if name[0].lower() in whitelist:
        print(name)

Upvotes: 1

Related Questions