Name Formatting in Python with String Splits

I have gotten mostly through this assignment but I am stuck as to obtain the proper outputs.

This assignment wishes that if the inputs are a full name, that the outputs are "last name, first initial. last initial. If the input was Stacy Estel Graham, the expected output should be Graham, S.E.

"Many documents use a specific format for a person's name. Write a program whose input is:

firstName middleName lastName

and whose output is:

lastName, firstInitial.middleInitial."

full_name = input()
mod_name = full_name.split(' ')
last_name= mod_name.pop(-1)
mod_name.join('.')
print(last_name)
print(mod_name)

I am completely lost on how to proceed.

4

4 Answers

You need to use '.'.join() to get the initials added.

To extract only the first char from the name, you can do mod_name[i][:1] where i is the index from 0 until last name - 1.

You can do something like this:

full_name = input('Enter your full name :')
mod_name = full_name.split(' ')
temp = '.'.join([mod_name[i][0] for i in range (0, len(mod_name) - 1)])
if temp == '':
    print (mod_name[-1])
else:
    print (mod_name[-1] + ', ' + temp + '.')

Here are some of the sample runs:

Enter your full name :Stacy Estel Sugar Graham
Graham, S.E.S.

Enter your full name :Stacy Estel Graham
Graham, S.E.

Enter your full name :Stacy Graham
Graham, S.

Enter your full name :Graham
Graham
2

Use:

def format_name(name):
    names = name.split()
    return f"{names[-1]}, {''.join([f'{i[0]}.' for i in names[:-1]])}"

Examples:

format_name('Stacy Estel Graham')
# > 'Graham, S.E.'

format_name('Randall McGrath')
# > 'McGrath, R.'

this code help you,but middle name is must for every person for creating your desire output

import re
s="Stacy Estel Graham"
words=s.split()
k=re.findall("[A-Z]",s)
p=words[-1]+","+k[0]+"."+k[1]
print(p)

Output:

Graham,S.E
2

Not with re :

full_name = input()
mod_name = full_name.split(' ')
last_name= mod_name.pop(-1)
first_inital = mod_name[0][0]
if len(mod_name) >= 2:
    middle_inital = mod_name[1][0]
    print(f'{last_name}, {first_inital}.{middle_inital}')
else:
    print(f'{last_name}, {first_inital}.')

You can use string indexing and f' string format.

Input:

Hello World Python

Output:

Python, H.W.
5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest