Reputation: 184
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.
Upvotes: 14
Views: 27329
Reputation: 12018
I'd look into using the nameparser library. It makes extracting human names a walk in the park...
from nameparser import HumanName
# Here's a full name, with a nickname
full_name = 'Mr. Lin-Manuel "The Boss" Miranda'
# Extract values
parsed_name = HumanName(full_name)
# Get just the first and last name
f_name = parsed_name.first
l_name = parsed_name.last
print(f_name, l_name)
# Lin-Manuel Miranda
# ------------------------------
# If you want to see everything:
parsed_name.as_dict()
{'title': 'Mr.',
'first': 'Lin-Manuel',
'middle': '',
'last': 'Miranda',
'suffix': '',
'nickname': 'The Boss'}
Upvotes: 5
Reputation: 5666
You can use str.partition that guarantee three tuple output in the format:
(part before separator, separator itself, part after separator)
>>> "a".partition(" ")
>>> ('a', '', '')
>>> "a b".partition(" ")
>>> ('a', ' ', 'b')
>>> "a b c".partition(" ")
>>> ('a', ' ', 'b c')
Upvotes: 7
Reputation: 43494
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
Upvotes: 13