How to convert a weird string to integer
Question:
Sorry for the possible repeats of the question. I have a weird string, for example:
'[23, 14, 34]'
ps: there is a comma "," and a space " " separating each number. The whole thing is recognized as string.
I want to convert it into a list of integers:
[23, 14, 34]
Any insights? Thanks in advance.
Answers:
You can use eval().
Your code should looks like this:
list_str = '[2, 43, 3]'
eval(list_str)
method eval
makes a python interpretation of a string, therefore if the string is a well-formed python string, it will make a good interpretation, including the conversion of strings to data.
input_list = "[2, 43, 3]"
final_list = eval(input_list)
In the previous example, final_list value will be [2, 43, 3]
.
Using json.loads()
import json
ini_list = "[1, 2, 3, 4, 5]"
print ("initial string", ini_list)
print (type(ini_list))
res = json.loads(ini_list)
print ("final list", res)
print (type(res))
Sorry for the possible repeats of the question. I have a weird string, for example:
'[23, 14, 34]'
ps: there is a comma "," and a space " " separating each number. The whole thing is recognized as string.
I want to convert it into a list of integers:
[23, 14, 34]
Any insights? Thanks in advance.
You can use eval().
Your code should looks like this:
list_str = '[2, 43, 3]'
eval(list_str)
method eval
makes a python interpretation of a string, therefore if the string is a well-formed python string, it will make a good interpretation, including the conversion of strings to data.
input_list = "[2, 43, 3]"
final_list = eval(input_list)
In the previous example, final_list value will be [2, 43, 3]
.
Using json.loads()
import json
ini_list = "[1, 2, 3, 4, 5]"
print ("initial string", ini_list)
print (type(ini_list))
res = json.loads(ini_list)
print ("final list", res)
print (type(res))