2

I have a list containing numbers the type of which is string. How can I convert the input to a list of integers?

input:

'[1, 3, 6, 8]'

desired output:

[1, 3, 6, 8]

6 Answers6

4
import ast


my_list = ast.literal_eval('[1, 3, 6, 8]')

Another option is the builtin function eval() but ast.literal_eval() is safer. You can read more here.

Divyesh Peshavaria
  • 589
  • 1
  • 5
  • 13
1

You could use eval() here, and directly evaluate your string input:

inp = '[1, 3, 6, 8]'
output = eval(inp)
print(output)  # [1, 3, 6, 8]

Another approach, using re.findall:

output = [int(x) for x in re.findall(r'\d+', x)]
print(output)  # [1, 3, 6, 8]
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Use Regex

ip ='[1, 3, 6, 8]'

import re
opt = [int(a) for a in re.findall("\d+",ip)]
print(opt)
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
theunknownSAI
  • 300
  • 1
  • 4
1

I suggest to use from the JSON standard library the method json.loads:

import json

string = '[1, 3, 6, 8]'
res = json.loads(string)
print(res)
#=> [1, 3, 6, 8]

And got the required list of integers:

all([ isinstance(e, int) for e in res ])
#=> True
iGian
  • 11,023
  • 3
  • 21
  • 36
0

Using regex re.findall this can be achieved as below:

import re
test_string = '[1, 3, 6, 8]'
res = re.findall(r'\d+', test_string)
# Map every entry to int
res = list(map(int, res))
  
print (res)
Bhagyesh Dudhediya
  • 1,800
  • 1
  • 13
  • 16
0

If you want a safe way of doing so without importing any libraries:

s = '[1, 3, 6, 8]'
print(list(map(int, ''.join(i if i.isdigit() else ' ' for i in s).split())))

Output:

[1, 3, 6, 8]

Explanation:

Lets have a look at the line:

list(map(int, ''.join(i if i.isdigit() else ' ' for i in s).split()))

On the outside we are merely mapping a list of strings to integers, so lets get rid of that part first:

''.join(i if i.isdigit() else ' ' for i in s).split()

Now we can see that we are replacing every character in the s string that is not a digit with a whitespace, and then we are splitting the string by whitespaces, resulting in

['1', '3', '6', '8']

which can then be mapped to a list of integers.

Red
  • 26,798
  • 7
  • 36
  • 58