Reputation: 3
say that i have a string with e.g first name surname
string = "Jessica Tree, Jefferson True, Mike Will"
how do i make a list taking only first or last name?
final = ["Jessica", "Jefferson", "Mike"]
or
final = ["Tree", "True", "Will"]
Upvotes: 0
Views: 28
Reputation: 377
You can use split
to split a string on a character, which gives you a list of all the whole names. Then you loop through the names, remove the whitespace before and after the whole name with strip
, use split
again but now on the whitespace in the whole name and use either the first (index 0) or last (index 1) name:
name_type = 0 # =0 for first name, =1 for last name
string = "Jessica Tree, Jefferson True, Mike Will"
final = [name.strip().split(" ")[name_type] for name in string.split(",")]
print(final)
Out:
['Jessica', 'Jefferson', 'Mike']
Upvotes: 1
Reputation: 1217
name_string = "Jessica Tree, Jefferson True, Mike Will"
full_name_list = name_string.split(",")
new_list = []
for name in full_name_list:
new_list.append(name.split()[0])
Upvotes: 0
Reputation: 1893
You can use split()
.
string = "Jessica Tree, Jefferson True, Mike Will"
final = [name.strip().split(" ")[0] for name in string.split(",")]
Upvotes: 0