Home > Software engineering >  How to make a string into a list with only first part of the string
How to make a string into a list with only first part of the string

Time:09-27

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]

CodePudding user response:

You can use split().

string = "Jessica Tree, Jefferson True, Mike Will"
final = [name.strip().split(" ")[0] for name in string.split(",")]

CodePudding user response:

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])

CodePudding user response:

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']
  • Related