Reputation: 29
I want to create a function that removes all of the middle name and leaves the First and Last name when given the format First, Middle, Last.
So far, I have
def clearmidname(listnames):
for name in listnames:
name = name.split()
del name[1]
new = " ".join(name)
return new
For example,
listnames = ["Orpah Gail Winfrey", "Montero Lamar Hill", "Pablo Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Cipriano de la Santísima Trinidad Ruiz y Picasso"]
print(clearmidname(listnames))
would give me
["Orpah Winfrey", "Montero Hill", "Pablo Picasso"]
Upvotes: 2
Views: 245
Reputation: 261
You can do this in one Pythonic line:
first_last_names_list = [name.split()[0]+" "+name.split()[-1] for name in listnames]
Upvotes: 0
Reputation: 95872
This is pretty simple, you can jsut .split
(perhaps using re.split
if there are complicated word boudaries) and just use extended iterable to seperate the first and last words from the middle:
>>> names = ["Orpah Gail Winfrey", "Montero Lamar Hill", "Pablo Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Cipriano de la Santísima Trinidad Ruiz y Picasso"]
>>> for name in names:
... first, *middle, last = name.split()
... print(f"{first} {last}")
...
Orpah Winfrey
Montero Hill
Pablo Picasso
So to create the list, just:
new = []
for name in names:
first, *_, last = name.split()
new.append(f"{first} {last}")
You can also use a list comprehension:
[f"{first} {last}" for name in names for first, *_, last in [name.split()]]
Upvotes: 1
Reputation: 892
Using similar logic with your code, with some modifications:
p.s. I added an "Orpah Gail G Winfrey" into the "listnames" to illustrate my point 2.
def clearmidname(listnames):
new = []
for name in listnames:
name = name.split()
new.append(" ".join([name[0], name[-1]]))
return new
listnames = ["Orpah Gail G Winfrey", "Orpah Gail Winfrey", "Montero Lamar Hill", "Pablo Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Cipriano de la Santísima Trinidad Ruiz y Picasso"]
print(clearmidname(listnames))
Result:
['Orpah Winfrey', 'Orpah Winfrey', 'Montero Hill', 'Pablo Picasso']
Upvotes: 0
Reputation: 1732
def clearmidname(listnames):
retlist=[]
for name in listnames:
name = name.split(" ")
retlist.append(name[0] + " " + name[-1])
return retlist
Upvotes: 2
Reputation: 520918
Your problem is a good candidate for a regex replacement:
# -*- coding: utf-8 -*-
import re
listnames = ["Orpah Gail Winfrey", "Montero Lamar Hill", "Pablo Diego José Francisco de Paula Juan Nepomuceno María de los Remedios Cipriano de la Santísima Trinidad Ruiz y Picasso"]
output = [re.sub(r' \S+(?= )', '', name) for name in listnames]
print(output) # ['Orpah Winfrey', 'Montero Hill', 'Pablo Picasso']
Upvotes: 0