Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string of space- and comma- separated numbers into a list of int? [duplicate]

I have a string of numbers, something like:

example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11' 

I would like to convert this into a list:

example_list = [0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11] 

I tried something like:

for i in example_string:     example_list.append(int(example_string[i])) 

But this obviously does not work, as the string contains spaces and commas. However, removing them is not an option, as numbers like '19' would be converted to 1 and 9. Could you please help me with this?

like image 656
Bart M Avatar asked Oct 12 '13 12:10

Bart M


People also ask

How do I turn a string into a list of numbers?

Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.

How do you convert a string separated by a comma to an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How do I change a comma separated string to a number?

To convert a comma separated string to a numeric array:Call the split() method on the string to get an array containing the substrings. Use the map() method to iterate over the array and convert each string to a number. The map method will return a new array containing only numbers.


1 Answers

Split on commas, then map to integers:

map(int, example_string.split(',')) 

Or use a list comprehension:

[int(s) for s in example_string.split(',')] 

The latter works better if you want a list result, or you can wrap the map() call in list().

This works because int() tolerates whitespace:

>>> example_string = '0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11' >>> list(map(int, example_string.split(',')))  # Python 3, in Python 2 the list() call is redundant [0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11] >>> [int(s) for s in example_string.split(',')] [0, 0, 0, 11, 0, 0, 0, 0, 0, 19, 0, 9, 0, 0, 0, 0, 0, 0, 11] 

Splitting on just a comma also is more tolerant of variable input; it doesn't matter if 0, 1 or 10 spaces are used between values.

like image 98
Martijn Pieters Avatar answered Oct 07 '22 07:10

Martijn Pieters