Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have to make a code taking a name and turning it into a last name, first initial and middle initial format

I have to make a code taking a name and turning it into a last name, first initial, middle initial format. My code works assuming there is a middle name but breaks if not provided a middle name. Is there a way to ignore not having a middle name and to just default to last name and first initial? I’m super new to python3 so I’m sorry if my code is uber bad.
Heres my code :

your_name = input()
broken_name = your_name.split()
first_name = broken_name[0]
middle_name = broken_name[1]
last_name = broken_name[2]

middle_in = middle_name[0]
first_in = first_name[0]
print(last_name+',',first_in+'.'+middle_in+'.' )

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use an if else statement to check how long broken_name is.
Try:

your_name = input()
broken_name = your_name.split()
if len(broken_name) > 2:
    first_name = broken_name[0]
    middle_name = broken_name[1]
    last_name = broken_name[2]

    middle_in = middle_name[0]
    first_in = first_name[0]
    print(last_name+', ',first_in+'. '+middle_in+'.'
else:
    first_name = broken_name[0]
    last_name = broken_name[1]
    first_in = first_name[0]
    print(last_name+', ',first_in+'.')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading