Slickmind
Slickmind

Reputation: 444

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 a heart doctor

to

Christina Acosta, M.D. is a heart doctor

Expected Output:

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

Upvotes: 0

Views: 2175

Answers (3)

aaldilai
aaldilai

Reputation: 271

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

Upvotes: 0

Han Jinn
Han Jinn

Reputation: 41

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

Upvotes: 0

blhsing
blhsing

Reputation: 106553

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

Upvotes: 1

Related Questions