'Splitting a name into first, middle and last name using Python

So i am basically asking that i have a name and i need to split it into three parts and store it into three different variables using Python.

For example:

Name= "John Wayne Smith"

Then the desired output should be:

First name= John

Middle Name= Wayne

Last name = Smith

Additionally I want to put a check that if for some person middle name is not there then it should be blank.



Solution 1:[1]

We can use following regular expression:

(?P<First>\S+)\s(?:(?P<Middle>\S*)\s)?(?P<Last>\S+)$

Which looks for a first and last name, and optionally a middle name.


Example

import re

s = "John Wayne Smith"
s2 = "John Smith"

p = re.compile(r"(?P<First>\S+)\s(?:(?P<Middle>\S*)\s)?(?P<Last>\S+)$")
p.match(s).groupdict()
# {'First': 'John', 'Middle': 'Wayne', 'Last': 'Smith'}

p.match(s2).groupdict()
# {'First': 'John', 'Middle': None, 'Last': 'Smith'}

Please note that match will match the entire string from start to end. Please make sure to clean and validate your inputs beforehand, as regular expressions are somewhat brittle to inputs they don't expect.

Solution 2:[2]

The library nameparse is the perfect solution for your question. You can install it by

pip install nameparser

In your code, import this library as:

from nameparser import HumanName

name = "John Wayne Smith"
name_parts = HumanName(name)
name_parts.title
name_parts.first
name_parts.middle
name_parts.last
name_parts.suffix
name_parts.nickname
name_parts.surnames  # (middle + last)
name_parts.initials  # (first initial of each name part)

Solution 3:[3]

Python has a feature called "unpacking" which allows you to destructure objects from a list. The list in question is from calling the split method on the string. It takes a string to split with. To unpack, you must have a declaration of the form [a, b, c] = list where a, b and c are objects you wish to unpack (in order). So your code is

[first, middle, last] = 'John Wayne Smith'.split(' ')

Solution 4:[4]

You can use str.split and len check on the result:

name = "John Wayne Smith"
parts = name.split(maxsplit=3)
if len(parts) == 3:
    first, middle, last = parts
else:
    first = parts[0]
    middle = ""
    last = parts[-1]
print([first, middle, last])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cs95
Solution 2 Muhammad Afzaal
Solution 3
Solution 4