Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Splitting a string of names separated by spaces and commas

Tags:

python

django

I have an API feeding into my program into a django many to many model field. The names of the individuals within my database are structured with a separated first name and last name. However, the API is sending a bulk list of names structured as as a string list as so: "Jones, Bob Smith, Jason Donald, Mic" (Last name-comma-space-first name-space-new last name- etc.)

How would I separate this string in a way that would allow me to filter and add a particular user to the many-to-many field?

Thanks!!

like image 600
mg2019 Avatar asked Dec 21 '25 18:12

mg2019


1 Answers

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

like image 98
Paulloed Avatar answered Dec 23 '25 08:12

Paulloed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!