Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python split full name into two variables with possibly multi-word last name

I have a list of full names which I am splitting into two variables currently like so:

first, last = full_name.split(" ")

which works only if full_name is two words when split, otherwise I get. Is there a concise way to account for a name with more parts to keep first as the first word and last as the rest of the words? I could do it with an extra line or two but I was wondering if there was an elegant way.

like image 758
Frank Matranga Avatar asked Mar 13 '18 03:03

Frank Matranga


1 Answers

Since you're using Python3, you can also use Extended Iterable Unpacking.

For example:

name = "John Jacob Jingleheimer Schmidt"
first, *last = name.split()
print("First = {first}".format(first=first))
#First = John
print("Last = {last}".format(last=" ".join(last)))
#Last = Jacob Jingleheimer Schmidt

This stores everything after the first element of the split string in last. Use " ".join(last) to put the string back together.

It also works if there's only two elements to unpack.

name = "John Schmidt"
first, *last = name.split()
print("First = {first}".format(first=first))
#First = John
print("Last = {last}".format(last=" ".join(last)))
#Last = Schmidt

Or if you wanted first, middle, and last:

name = "John Jacob Jingleheimer Schmidt"
first, middle, *last = name.split()
print("First = {first}".format(first=first))
#First = John
print("Middle = {middle}".format(middle=middle))
#Middle = Jacob
print("Last = {last}".format(last=" ".join(last)))
#Last = Jingleheimer Schmidt
like image 105
pault Avatar answered Oct 22 '22 16:10

pault