Skip to content Skip to sidebar Skip to footer

Convert String Of Numbers To List Of Numbers

l='2,3,4,5,6' expecting: [2,3,4,5,6] In python how can I convert into the above format the first one is a string of some numbers I am expecting a list of same numbers.

Solution 1:

As simple as this:

in Python2:

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

and in Python3 simply wrapped with a parentheses:

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

Solution 2:

You could use a list comprehension:

l='2,3,4,5,6'

result = [int(i) for i in l.split(',')]
print(result)

Output

[2, 3, 4, 5, 6]

The above is equivalent to the following for loop:

result = []
for i in l.split(','):
    result.append(i)

As an alternative you could use map:

l = '2,3,4,5,6'
result = list(map(int, l.split(',')))
print(result)

Output

[2, 3, 4, 5, 6]

Solution 3:

Try this simple and direct way with a list comprehension.

list_of_numbers = [int(i) for i in l.split(",")]

Alternatively, you can fix up the string so it becomes a "list of strings", and use literal_eval:

import ast
s = "[" + l + "]'
list_of_numbers = ast.literal_eval(s)

Solution 4:

you can use map and split to convert.

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

Example:

l='2,3,4,5,6'
print(map(int, l.split(',')))

output

[2, 3, 4, 5, 6]

Solution 5:

You can also use map like this:

list(map(int,[i for i in l if i.isdigit()]))

Post a Comment for "Convert String Of Numbers To List Of Numbers"