In a list of names(3 full names) I need to extract the first and middle initials with the last name in full and return all this as a string...Here is what I have tried but I keep getting just one name and not the three when I iterate...Pls help ..new to python,and this is driving me bunkers.. My code below:
def fancy_me(name_string):
name = ', '.join(name_string)
name_list = name.split()
name_sublist = name_list[:3]
name_sublist2 = name_list[3:6]
name_sublist3 = name_list[-3:]
new_namelist = [name_sublist, name_sublist2, name_sublist3]
for x in new_namelist:
new_list = []
first = (x[0][0])
mid = (x[1][0])
last = (x[2])
return first ' .' mid '. ' last
print(fancy_me(["First Middle Last", "David Andrew Joyner", "George P Burdell"]))
my output: G .P. Burdell
Desired output: F. M. Last, D. A. Joyner, G. P. Burdell
CodePudding user response:
You have a couple of issues here. First, you are joining at the wrong time - you want to do the comma join at the end rather than the beginning. This is getting in the way of the splitting you're doing. Then it looks like you have wrong expectiations of how Python will deal with the inputs above your loop. It will not do any looping over the inputs automatically.
I'd break out the two different functions as follows:
def initialize(name):
first, middle, last = name.split() # note this assumes all names will only be three parts
return f"{first[0]}. {middle[0]}. {last}"
def fancy_me(namelist):
return ", ".join(initialize(name) for name in namelist)
CodePudding user response:
If you want to eliminate the assumption in @chthonicdaemon's answer that all names consist of three parts, you can adapt the solution in the following way:
def initialize(name: str) -> str:
parts = name.split()
return ". ".join(part[0] for part in parts) parts[-1][1:]
def fancy_me(namelist: list[str]) -> str:
return ", ".join(initialize(name) for name in namelist)