how can I convert a string to an int in python say I have this array
['(111,11,12)','(12,34,56)'] to [(111,11,12),(12,34,56)]
Any help will be appreciated thanks
how can I convert a string to an int in python say I have this array
['(111,11,12)','(12,34,56)'] to [(111,11,12),(12,34,56)]
Any help will be appreciated thanks
import ast
a = "['(111,11,12)','(12,34,56)']"
[ast.literal_eval(b) for b in ast.literal_eval(a)]
# [(111, 11, 12), (12, 34, 56)]
EDIT: if you have a list of strings (and not a string), just like @DSM suggests, then you have to modify it:
a = ['(111,11,12)','(12,34,56)']
[ast.literal_eval(b) for b in a]
# [(111, 11, 12), (12, 34, 56)]
You could try some re:
import re
src = ['(111,11,12)', '(12,34,56)']
[tuple([int(n) for n in re.findall(r"(\d+),(\d+),(\d+)", s)[0]]) for s in src]
By reading your question I see you have a list of strings:
l = ['(111,11,12)','(12,34,56)']
and you want to convert that to a list of numbers...
# some cleaning first
number_list = [x.strip('()').split(',') for x in l]
for numbers in number_list:
numbers[:] = [int(x) for x in numbers]
print number_list
Sorry for that list comprehension parsing, if you're new that looks weird but is a very common python idiom and you should get familiar with it.
Have fun!
def customIntparser(n):
exec("n="+str(n))
if type(n) is list or type(n) is tuple:
temps=[]
for a in n:
temps.append(customIntparser(str(a)))
if type(n) is tuple:
temps=tuple(temps)
return temps
else:
exec("z="+str(n))
return z
Sample tests:
>>>s = "['(111,11,12)','(12,34,56)']"
>>>a=customIntparser(s)
>>> a
# [(111, 11, 12), (12, 34, 56)]
>a[0][1]
# 11
You can convert a string to an int with the int() keyword:
Python 2.7.2 (default, Jun 20 2012, 16:23:33)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> int('42')
42
But the example you give seems to indicate that you want to do this for an entire tuple, not a single integer. If so, you can use the builtin eval function:
>>> eval('(111,111)')
(111, 111)