Home > database >  How to select an index of an element inside an element of a list of a user's string input separ
How to select an index of an element inside an element of a list of a user's string input separ

Time:12-07

User's input should be a list of full names separated by comma (same input as 2nd code below). I want to print those names in separate lines in the format of: lastname "," firstname middlename (if applicable).

I have written two codes but I can't seem to bring them together to my desired output:

1st code - Names are sorted as surname comma firstnames (includes middlename if given):

while True:
    name = input("Enter your full name here:").strip().title()

    words_in_name = name.split()
    surname = words_in_name[-1]
    firstname = words_in_name[:-1]

    name_sorted = surname, " ".join(firstname)

    print(name_sorted)
Enter your full name here: John Doe
('Doe', 'John')

2nd code - List of fullnames are printed in separate lines and comma that separates them in the input are removed:

while True: 
    DL_names = input("Enter the list of names you want to add to the DL:").strip().title()

    print(*DL_names.split(","), sep='\n')
Enter the list of names you want to add to the DL:John Doe, Jane Doe 

 John Doe
  Jane Doe

CodePudding user response:

You already have all pieces of code to make it work. You could make the code a little shorter by assigning surname and firstname to their respective index of the split string (also you should split on , first):

DL_names = input("Enter the list of names you want to add to the DL:").strip().title()
for full_name in DL_names.split(','):
    *firstname, surname = full_name.split()
    print(f"{surname}, {' '.join(firstname)}")

Output:

Doe, John
Doe, Jane
  • Related