authors = ['Audre Lorde', 'William Carlos', 'Gabriela Mistral', 'Jean Toomer', 'An Qi', 'Walt Whitman', 'Shel Silverstein', 'Carmen Boullosa', 'Kamala Suraiyya', 'Langston Hughes', 'Adrienne Rich', 'Nikki Giovanni']
In this list, I want to get the names that have last names start with (let's say 'S') in Python. How do I do that? To be honest, I have no clue where to start as I am still a beginner, I tried join and split but they brought only the last name itself.
CodePudding user response:
For your learning.
The list in question is not well formed.
Let's assume it is well formed. Below is simple example.
authors = ['Audre Lorde', 'William Carlos', 'Gabriela Mistral', 'Jean Toomer']
newlist = [x for x in authors if x.split(" ")[1].startswith('C')]
CodePudding user response:
Matching names can be difficult because you can have multiple first and last names, see this page for a nice read Falsehoods Programmers Believe About Names.
If you can have a single name as well, you can take the last entry after splitting:
authors = ['Audre Lorde', 'William Carlos', 'Gabriela Mistral', 'Jean Toomer', 'Cher']
print([a for a in authors if a.split(" ")[-1].startswith('C')])
If you want to for example check the number of splitted parts and do not want to allow single names:
for a in authors:
parts = a.split(" ")
if len(parts) > 1 and parts[1].startswith('C'):
print(parts[1])