Python splits the full name into two variables with a possibly verbose name

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

first, last = full_name.split(" ")

which works only if full_name- two words in a split, otherwise I get. Is there a condensed way to account for a name with a lot of parts to save firstas the first word and lastas the rest of the words? I could do this with an extra line or two, but I was wondering if there was an elegant way.

+4
source share
5 answers

Look at the second split option

first, last = "First Last Second Last".split(" ", 1)

If it full_namecan be in one word:

name_arr = full_name.split(" ", 1)
first = name_arr[0]
last = name_arr[1] if len(name_arr) > 1 else ""
+6
source

str.partition, :

(part before separator, separator itself, part after separator)

>>> "a".partition(" ")
>>> ('a', '', '')

>>> "a b".partition(" ")
>>> ('a', ' ', 'b')

>>> "a b c".partition(" ")
>>> ('a', ' ', 'b c')
+5

:

first, last = full_name.split(" ", 1)
+2

Python3, Extended Iterable Unpacking.

:

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

last. " ".join(last), .

, .

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

, :

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
+2

, , , . , , - - https://github.com/sunlightlabs/name-cleaver

It works well by splitting the name into parts such as name, first name, last name, etc.

0
source

Source: https://habr.com/ru/post/1694796/


All Articles