9

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']
Vincent Savard
  • 34,979
  • 10
  • 68
  • 73
Peter Yost
  • 109
  • 1
  • 1
  • 8

6 Answers6

13

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']
gtlambert
  • 11,711
  • 2
  • 30
  • 48
3

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
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Antoine
  • 1,070
  • 7
  • 11
1

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)
Haris
  • 12,120
  • 6
  • 43
  • 70
1

or you can simply do

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

and it converts the thing you typed it as a list

OupsMajDsl
  • 11
  • 1
-1
a=list(input()).

It converts the input into a list just like when we want to convert the input into an integer.

a=(int(input())) #typecasts input to int
Community
  • 1
  • 1
Odin
  • 1
  • 2
-1

using list comprehension,

magicInput = [_ for _ in input("Enter String:")]

print('magicList = [{}]'.format(', '.join(magicInput)))

produces

Enter String:python rocks
magicList = [p, y, t, h, o, n,  , r, o, c, k, s]

You can use str.join() to concatenate strings with a specified separator. Furthermore, in your case, str.format() may also help. However the apostrophes will not interfere with anything you do with the list. The apostrophes show that the elements are strings.

Method 2:

magicInput = ','.join(input('Enter String: '))
print(f'\nmagicList: [{magicInput}]')

Edit 1:

user_input = input("Enter String:")
magic_list = list(user_input)

print(f'magic_list = {magic_list}')

This code captures the user input as a string and then converts it into a list of characters using list().

Subham
  • 397
  • 1
  • 6
  • 14