1

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

4

5 回答 5

8
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)]
于 2012-12-27T14:50:05.997 回答
0

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]
于 2012-12-27T15:21:57.790 回答
0

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.

于 2012-12-27T15:58:09.057 回答
0

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
于 2012-12-27T17:26:05.180 回答
-2

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)
于 2012-12-27T14:52:38.567 回答