Python - Convert string with numbers into a list o

2020-04-01 06:41发布

I've read several questions about this on SO, however, none of them worked out for me - I guess I'm doing something wrong.

I have a string with numbers separated with commas and spaces which looks like this:

my_string = '32, 76, 82, 19, 25'

Now what I would like to have is a list of integers of the numbers in the string above, so I can extract single integers from it like this:

print my_list[2]
>>>82

or

print my_list[4]
>>>25

Thanks in advance!

2条回答
一纸荒年 Trace。
2楼-- · 2020-04-01 06:48

The most pythonic way would be

[int(i) for i in my_string.split(',')]

Of course you can build a simple for loop if you prefer, like

mylist = []
for i in my_string.split(','):
    mylist.append(int(i))

There are plenty of possibilities

查看更多
够拽才男人
3楼-- · 2020-04-01 07:01

Split the problem into two parts.

1 Split the text into a list with the data you need and filter the other.

num_list = my_string.split(',')

2 Convert the data into what type you want it

integers = [int(x) for x in num_list]

Then you might clean it up

integs = [int(x) for x in my_string.split(',')]
查看更多
登录 后发表回答