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!!
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With