How do i print a list of names (from user input) in the format of "First Initial. Last Name"? (python 3)

Question:

An example would be of the output I am looking for is:

Enter list of names:

Tony Stark, Steve Rodgers, Wade Wilson

Output

T. Stark
S. Rodgers
W. Wilson

I would also appreciate if you could explain how the code for this works because I am new to coding and want to understand what I’m doing rather than just copying.

Asked By: Ryan

||

Answers:

Try this.

lst = ['Tony Stark', 'Steve Rodgers', 'Wade Wilson']

def f(s): # if s='Tony Stark'
    s = s.split(' ') #
    return s[0][0]+'. ' + ' '.join(s[1:]) # s[0][0] is T and then I add '. ' to 'T' and then I convert the rest of the word list to string using the join function an add it to the string.
outLst = map(f,lst)

print(*outLst,sep='n')

Output

T. Stark
S. Rodgers
W. Wilson
  1. First I use the map function to iterate through all elements and execute a function f for all element one by one. (You can also use list comprehension).
  2. In the f function I convert the string to a list using the split function.
  3. Then I return the modified string.
Answered By: codester_09

You can do something like this,

In [32]: l = ['Tony Stark', ' Steve Rodgers', ' Wade Wilson']

In [33]: [f'{i.split()[0][0]}.{i.split()[1]}' for i in l]
Out[33]: ['T.Stark', 'S.Rodgers', 'W.Wilson']
Answered By: Rahul K P

First of all you need to read the names from the user:

names_str = input("please enter names separated by commas: ")

Now, the first step to separate them to have a list of "FirstName LastName"s. You’d better first replace all ", " with "," to avoid unnecessary spaces.

first_lasts = names_str.replace(", ", ",").split(",")

Next, you want to print the First Initial. + Last name.

for first_last in first_lasts:
    first_name, last_name = first_last.split(" ")
    print(f"{first_name[0]}. {last_name}")

There are many more advanced and shorter ways to do it but since you mentioned you’re still learning I think this one is a good starting point 🙂

result:

T. Stark
S. Rodgers
W. Wilson
Answered By: Mohammad

The question says "Enter list of names" which I take to be a comma delimited single string of input. If that’s the case then:

list_of_names = 'Tony Stark, Steve Rodgers, Wade Wilson'

for forename, surname in map(str.split, list_of_names.split(',')):
    print(f'{forename[0]}. {surname}')

Output:

T. Stark
S. Rodgers
W. Wilson
Answered By: OldBill

Ok, so firstly you need to call a built-in (native to the Python language) input function, which will open a text input stream for you and you will be able to provide some data to the program via console and/or terminal. You can read about built-in functions and input function specifically here and here. The code you need to start with in order to open mentioned stream can look as follows:

names = input('Type names separated by commas (e.g. Tony Stark, Thor Odinson): ')

When you will run your program, you will see in the console:

Type names separated by commas (e.g. Tony Stark, Thor Odinson): 

Now you can provide the names you want to provide after the colon, e.g. Tony Stark, Thor Odinson and hit enter/return keyboard key when you’re done in order to close the input stream. After this operation, the data you’ve provided will be represented as a sequence/string of characters of a built-in data type called str, which is an abbreviation from string (native to Python language). For more information about built-in data types in Python language see this page. Nevertheless, you can check your data by typing:

print(names, type(names))

…which will give you an output:

Tony Stark, Thor Odinson <class 'str'>

Finally, in order to transform provided data in a way you want it to be transformed we need to cut it and organize in a specific way. First look at the code and later at the description of it below:

names = names.replace(', ', ',').split(',')
for name in names:
    first, last = name.split(' ')
    print(f'{first[0]}. {last}')

At the first line we replace commas followed by whitespaces to commas, and split the resulting sequence by commas, so we will get a list consisting of two elements:

['Tony Stark', 'Thor Odinson']

Now, what we need to do, is to iterate over the elements of the list, e.g. with the use of the for loop. Finally, we use a split method one more time to cut individual list elements into a first and last name, and we use f-String formatting to build output you wanted to achieve at the first place. You can read about f-String here. Hope this helps.

Answered By: Calcium Owl
lst_name = input("Enter a list of names: ")
#separete them in a list
lst = lst_name.split(",")

#get through each name
for names in lst:
     #strip from whitespaces front and end, then split in firstname and lastname
     f, l = names.strip().split(" ")
     #print result
     print(f"{f[0]}. {l}")
Answered By: A. Herlas

If your name contains more than two words, the following solution will help you to create initials for the first names and will display the last name as it is.

names_str = input("Please enter names separated by commas: ")
# names_str = 'Tony Stark, Steve Rodgers, Wade Wilson, James Earl Jones'

for name in names_str.split(','):  # taking names one by one splitting by ','
    first_names, last_name = name.strip().rsplit(' ', 1)  # trim the name and split first names and last name
    initials = '. '.join(first_name[0] for first_name in first_names.split(" "))  # setup initials of the first names
    name_with_initials = f'{initials}. {last_name}'  # concatenate initials with last name
    print(name_with_initials)

Output:

T. Stark
S. Rodgers
W. Wilson
J. E. Jones
Answered By: Kushan Gunasekera
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.