I have a list of items in a string with 2 columns and dozens of rows. I want to filter out every item from one of the columns. I think I can do this by applying the .split command on each row but if there's any better way to do this that doesn't involve regex I'd like to know.
Edit: I'm trying to do this with a list of names like:
"""Roy Theresa
Vincent Diana
Ralph Natalie
Eugene Brittany""" etc.
When I use:
head, sep, tail = nameList.partition(' ')
print(head)
It only returns the first name in the list. I want to apply that code to every line of the string so I can get the first name off every line instead of just the first one in the whole list.
CodePudding user response:
If you have a direct list like:
a = ["Roy Theresa","Vincent Diana","Ralph Natalie","Eugene Brittany"]
then all you have to do is :
for i in a:
print(i.split(" ")[0])
to get the first world from each element of the list.
But if you have a String like :
b = """Roy Theresa
Vincent Diana
Ralph Natalie
Eugene Brittany"""
First you must divide it into different names using splitlines() and repeat the top step once you get a list of names, like this:
new_list = b.splitlines()
for i in new_list:
print(i.split(" ")[0])
Your output will be:
Roy
Vincent
Ralph
Eugene