Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert user input into a list?

I'm wondering how to take user input and make a list of every character in it.

magicInput = input('Type here: ')

And say you entered "python rocks" I want a to make it a list something like this

magicList = [p,y,t,h,o,n, ,r,o,c,k,s]

But if I do this:

magicInput = input('Type here: ')
magicList = [magicInput]

The magicList is just

['python rocks']
like image 424
Peter Yost Avatar asked Feb 23 '16 16:02

Peter Yost


4 Answers

Use the built-in list() function:

magicInput = input('Type here: ')
magicList = list(magicInput)
print(magicList)

Output

['p', 'y', 't', 'h', 'o', 'n', ' ', 'r', 'o', 'c', 'k', 's']
like image 52
gtlambert Avatar answered Oct 17 '22 00:10

gtlambert


It may not be necessary to do any conversion, because the string supports many list operations. For instance:

print(magicInput[1])
print(magicInput[2:4])

Output:

y
th
like image 21
Antoine Avatar answered Oct 17 '22 00:10

Antoine


Another simple way would be to traverse the input and construct a list taking each letter

magicInput = input('Type here: ')
list_magicInput = []
for letter in magicInput:
    list_magicInput.append(letter)
like image 1
Haris Avatar answered Oct 17 '22 00:10

Haris


or you can simply do

x=list(input('Thats the input: ')

and it converts the thing you typed it as a list

like image 1
OupsMajDsl Avatar answered Oct 17 '22 01:10

OupsMajDsl