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
Source:stackexchange.com