0

I ask for a user to input names and I need to return them one a time from a list, but what happens is only single letters are returned instead of the full name.

Names = input("Enter names here: ")

The list I get is something like this,

Jim, John, Sarah, Mark

This is what I try,

print (Names[0])

What I get as a return

J

I want Jim as the return a nothing else.

3 Answers3

1

When input reads the data it will return a string, which you must break into a list. Thankfully strings have a method split just for that. Try:

Names = input("Enter names here: ")
Names = Names.split(',')
João Areias
  • 1,192
  • 11
  • 41
0

You can split the string on spaces or comma and other common delimiters using a simple regular expression. That gives you an array of strings, in case, the words.

Then you chose the first element of the array.

line="Jim, John, Sarah, Mark"           
words = re.split(r'[;,\s]\s*', line)
print (words[0])
plpsanchez
  • 339
  • 4
  • 10
0

"Names" variable stores the input as a string. Convert it into a list using:

names_list = Names.split(', ')
print(names_list[0])

However, this will only work if you enter names separated by a comma followed by a space. A better way is to create an empty list first and then append input elements to the list. Following is an example:

# Creating an empty list 
names_list = []

# Iterates till the input is empty or none
while True:
    inp = input("Enter name: ")
    if inp == "":
        break
    names_list.append(inp)

# Prints first element of the list
print(names_list[0])
Shradha
  • 2,232
  • 1
  • 14
  • 26