Trying to display initials in Python

I try to make sure that when a person types his name, only the initials are displayed in capital letters and are separated by a period. I can’t understand what is wrong with this code that 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()
+4
source share
4 answers

If you are on Python 2.x, you must exchange data for raw_input. Here's a faster way to achieve what you're aiming for by 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)
+8
source
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()
0
source

, , . , name name_list .

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()

, split(), ( ) . , , , .

0
source

I will try to explain why this happened, and not just give you a solution.

You use nameinstead name_list, when name_list- this is what you are going to use.

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

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


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

The first name is equivalent for both:

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

The left side corresponds to the first letter of the first letter:

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

The right side corresponds to 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 and second:

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

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

So just use name_listinstead name:

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

Source: https://habr.com/ru/post/1537240/


All Articles