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.
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
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