Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 735
Abhishek Mishra Avatar asked Sep 18 '25 06:09

Abhishek Mishra


1 Answers

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)
like image 158
Muhammad Afzaal Avatar answered Sep 19 '25 20:09

Muhammad Afzaal