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]
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.
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]
Use Regex
ip ='[1, 3, 6, 8]'
import re
opt = [int(a) for a in re.findall("\d+",ip)]
print(opt)
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
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)
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.