Skip to content Skip to sidebar Skip to footer

Extracting Name As First Name Last Name In Python

I have a text file with lines as: Acosta, Christina, M.D. is a heart doctor Alissa Russo, M.D. is a heart doctor is there a way to convert below line: Acosta, Christina, M.D. is

Solution 1:

You can use the follow regex to group the first and last names and substitute them in reverse order without the comma:

import re
data = '''Acosta, Christina, M.D. is a heart doctor
Alissa Russo, M.D. is a heart doctor'''print(re.sub(r"([a-z'-]+), ([a-z'-]+)(?=,\s*M.D.)", r'\2 \1', data, flags=re.IGNORECASE))

This outputs:

Christina Acosta, M.D. is a heart doctor
Alissa Russo, M.D. is a heart doctor

Solution 2:

testline = 'Acosta, Christina, M.D. is a heart doctor'
a = testline.split(',', 1)
b = a[1].split(',',1)
newstring = b[0]+' '+a[0]+','+ b[1]
print newstring

your output should be: Christina Acosta, M.D. is a heart doctor

Solution 3:

Try this

import re
pattern = "(\w+), (\w+), M.D. is a heart doctor"
my_string = "Acosta, Christina, M.D. is a heart doctor"
re.sub(pattern, r"\2 \1, M.D. is a heart doctor", my_string)

In the pattern we specify two groups, and then we use them in the substituting by referencing them with \1 and \2

Post a Comment for "Extracting Name As First Name Last Name In Python"