user3534918
user3534918

Reputation: 73

Trying to display initials in Python

I'm trying to make this so that when a person types their name just the initials display capitalized and separated by a period. I can't figure out what is wrong with this code I wrote... help pls!

def main():

name = input('Type your name and press ENTER. ')
name_list = name.split()

print(name_list)

first = name[0][0]
second = name[1][0]
last = name[2][0]

print(first,'.', second,'.')

main()

Upvotes: 4

Views: 20536

Answers (4)

matt
matt

Reputation: 2449

I'll try to explain why it occurred rather than just giving you the solution.

You're using name instead of name_list when name_list is what you're intending to use.

name for 'Amanda Leigh Blount' = 'Amanda Leigh Blount'

but name_list = name.split() = ['Amanda', 'Leigh', 'Blount']


So you get a difference in the two only on the middle/last name.

The first name is equivalent for both:

name[0][0] == name_list[0][0]

The left side matches the first letter of the first letter:

'Amanda Leigh Blount'[0][0] = 'A'[0] = 'A'

The right side matches the first letter of the first word.

['Amanda', 'Leigh', 'Blount'][0][0] = 'Amanda'[0] = 'A'


But for the second:

name[1][0] != name_list[1][0]

because the first & second are:

'Amanda Leigh Blount'[1][0] = 'm'[0] = 'm'

['Amanda', 'Leigh', 'Blount'][0][0] = 'Leigh'[0] = 'L'

So just use name_list instead of name:

first = name_list[0][0]
second = name_list[1][0]
last = name_list[2][0]

Upvotes: 0

keyser
keyser

Reputation: 19189

Here's a version similar to the one you have. Note that you were using name instead of name_list, and some hard-coded indexes.

def main():

    name = input('Type your name and press ENTER. ')
    name_list = name.split()

    for part in name_list:
        print(part[0].upper() + ". ", end="")
    print()

main()

It loops over the list you created with split(), and prints the first letter (in upper case) of each part of the name. The loop only makes sense if you want every part to be included of course.

Upvotes: 0

John
John

Reputation: 13699

def main():


    name = input('Type your name and press ENTER. ')
    name_list = name.split()

    print(name_list)

    first = name_list[0][0]
    second = name_list[1][0]
    last = name_list[2][0]

    print(first.upper(),'.', second.upper(),'.', last.upper()) 


main()

Upvotes: 0

agrinh
agrinh

Reputation: 1905

If you are on Python 2.x you should exchange input for raw_input. Here's a quicker way to achieve what you're aiming for assuming you're on Python 2.x:

def main():
    full_name = raw_input('Type your name and press ENTER. ')
    initials = '.'.join(name[0].upper() for name in full_name.split())
    print(initials)

Upvotes: 8

Related Questions