[Django]-Python – Splitting a string of names separated by spaces and commas

2πŸ‘

βœ…

This answer excludes the case where a first name or last name contains space (this case is much more complicated as you will have a word with a space on his left AND on his right).

You need to replace the -comma-space- by something without a space (because you also have a space between two different names).

string = "Jones, Bob Smith, Jason Donald, Mic"

names = []
for name in string.replace(', ', ',').split(' '): 
    name = name.split(',')
    last_name = name[0]
    first_name = name[1]
    names.append((last_name, first_name))
names

Output:
[('Jones', 'Bob'), ('Smith', 'Jason'), ('Donald', 'Mic')]

πŸ‘€Paulloed

1πŸ‘

You can use regex:

s = "Jones, Bob Smith, Jason Donald, Mic"

list(re.findall(r'(\S+), (\S+)', s))
# [('Jones', 'Bob'), ('Smith', 'Jason'), ('Donald', 'Mic')]
πŸ‘€Mykola Zotko

Leave a comment