简体   繁体   中英

Python parsing, convert string to list of integers

I'm using raw_input for the user to type in an integer, for example '123456' .

How do I convert the string number by number so I can put them in a list: [1,2,3,4,5] ?

Is the concept the same for two numbers like 12 , 34 , 56 ?

If you want to transform the string you read in from raw_input to a list of int ...

number = raw_input("Number? ")
li = [int(i) for i in number]

There's only a little bit more work that you have to do to expand it to multiple digits, but I leave that as an exercise for the reader.

if user enter the numbers Consecutive you you can use the following list comprehension :

>>> num=raw_input ("enter the numbers : ")
enter the numbers : 123459
>>> l=[int(i) for i in num]
>>> l
[1, 2, 3, 4, 5, 9]

and for numbers with len 2 that uses , as separator you need to split the input string then convert it to int :

>>> num=raw_input ("enter the numbers : ")
enter the numbers : 12,34,56
>>> l=[int(i) for i in num.split(',')]
>>> l
[12, 34, 56]

But there is another way , if you dont want to convert the numbers you can put your raw_input function inside a loop :

>>> l=[]
>>> for i in range (5):
...  l.append(int(raw_input('enter %dth number :'%i)))
... 
enter 0th number :1
enter 1th number :5
enter 2th number :12
enter 3th number :56
enter 4th number :2345
>>> l
[1, 5, 12, 56, 2345]

and if you want to get number with len 2 from one input you can use slicing :

>>> num=raw_input ("enter the numbers : ")
enter the numbers : 1234424
>>> [int(num[i:i+2]) for i in range(0,len(num),2)]
[12, 34, 42, 4]
s = '123456'
print(map(int,s))

s = '12,34,56'
print(map(int,s.split(",")))

[1, 2, 3, 4, 5, 6]
[12, 34, 56]


s = '123456'
print([int("".join(tup)) for tup in zip(s[::2],s[1::2])]

[12, 34, 56]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM