Derek Pruitt
Derek Pruitt

Reputation: 27

Convert full name input to last name + initials

Write a program in python whose input is:

firstName middleName lastName

and whose output is:

lastName, firstInitial.middleInitial.

Ex: If the input is:

Pat Silly Doe    

the output is:

Doe, P.S.  

If the input has the form:

firstName lastName

the output is:

lastName, firstInitial.

Ex: If the input is:

Julia Clark

the output is:

Clark, J.

all without using if then statements.

this is what I have so far which works for three names but not two names.

user_name = input(' ').split()

print('{}, {}.{}.'.format(user_name[2], user_name[0][0], user_name[1][0]))

Upvotes: 0

Views: 1735

Answers (4)

Buoy Rina
Buoy Rina

Reputation: 568

input_name = "First Second Third"
split_names = input_name.split(" ")
print(split_names[-1] + ", " + "".join([s[0].upper() +"." for s in split_names[:-1] ]))

Upvotes: 0

Vishal Singh
Vishal Singh

Reputation: 6234

If you just need a one-liner

f'{user_name.split()[-1]}, {".".join(word[0] for word in user_name.split()[:-1])}.'

Upvotes: 0

user9706
user9706

Reputation:

I would skip the dictionary (d) but it seems to be a requirement for you:

def initials(a):
    return ''.join(map(lambda s: s[0] + '.', a))


def abbreviate(s):
    l = s.split()
    d = {'lastName': l[-1], 'initials': initials(l[0:-1])}
    return '{}, {}'.format(d['lastName'], d['initials'])


for n in ('Pat Silly Doe', 'Julia Clark'):
    print(abbreviate(n))

and this will give you the output:

Doe, P.S
Clark, J.

Here is a fancier version using zip() to combine the keys and values and converted into a dictionary with dict():

def abbreviate(s):
    l = s.rsplit(maxsplit=1)
    d = dict(
        zip(
            ('lastName', 'initials'),
            (
                l[1],
                ''.join(map(lambda s2: s2[0] + '.', l[0].split()))
            )
        )
    )
    return f"{d['lastName']}, {d['initials']}"

Upvotes: 1

adamkwm
adamkwm

Reputation: 1173

As you do not use a dictionary in your code, I just provide a solution without dict.

name = input("Name: ").split()
print(f"{name.pop()}, {''.join(n[0] + '.' for n in name)}")

name.pop() gets the last name in list, n[0] + '.' gets the initials for the remaining names and adds a dot after them, then we use join() to combine these initials.

Test run:

Name: Pat Silly Doe
Doe, P.S.
Name: Julia Clark
Clark, J.

Upvotes: 1

Related Questions