My code is supposed to spit out this format: 'Last Name, First Name MI' BUT... If the middle initial is just a single letter (eg name = "Bala X Krish"), it should NOT put a period after the MI (should return "Krish, Bala X").
Right now, my code is returning 'Krish, Bala X.'
How can I fix it so that only during this specific instance of a single-letter MI, the end period is NOT added?
def modify(name):
"""
name is a string with zero or more spaces
with one space between each "word"
return string "last, first MI. MI. MI. ..."
where MI is middle initial
"""
NameLst = name.split()
MiddleNames = NameLst[1:-1]
initial = ""
if " " not in name:
return name
elif name.count(" ") == 1:
return NameLst[-1] + ", " + NameLst[0]
else:
MiddleNameCount = len(MiddleNames)
for MiddleName in MiddleNames:
Keep = MiddleName[0] + "."
if MiddleNameCount == 1:
initial = initial + Keep + " "
elif MiddleNameCount > 1:
if MiddleName[0:-2]:
initial = initial + Keep + " "
elif MiddleName[-1]:
initial = initial + Keep
x = NameLst[-1] + ", " + NameLst[0] + " " + initial
return x[0:-1]
Your code is way to complicate for this task. You can simply itterate over the middleNames and check their length:
def modify(name):
"""
name is a string with zero or more spaces
with one space between each "word"
return string "last, first MI. MI. MI. ..."
where MI is middle initial
"""
nameLst = name.split()
if len(nameLst) < 2:
return name
middleNames = nameLst[1:-1]
initial = f"{nameLst[-1]}, {nameLst[0]}"
for i in middleNames:
initial += f" {i[0]}"
if len(i) != 1: initial += '.'
return initial
Please remeber that the use of f-Strings ( f""
) for formatting is only available in python 3.6+, so you may want to use .format()
depending on the environment.
A simple fix would be to change this line:
Keep = MiddleName[0] + "."
to this:
Keep = MiddleName[0]
if len(MiddleName) > 1: Keep += "."
I have edited your code and made it way shorted to achieve your desired result in a clean and minimal way. Hope this helps.
def handle_middle_name(name):
if len(name.split()) == 3:
first, middle, last = name.split()[0], name.split()[1], name.split()[-1]
formatted_name = f"{last}, {first} {middle[0] + '.' if len(middle) > 1 else middle[0]}"
return formatted_name
else:
return "Your name doesn't have a middle name"
name = input("Enter your full name (including middle name): ")
print(handle_middle_name(name))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.