2012-12-27 177 views
2

我如何将字符串转换成int在python 说我有这个数组将字符串转换成int蟒蛇

['(111,11,12)','(12,34,56)'] to [(111,11,12),(12,34,56)] 

任何帮助将不胜感激感谢

+0

@closevoter:我看不出有任何理由为什么这应该也是本地化的,虽然你可以选择投为重复 – Abhijit

回答

0

你可以尝试一些重:

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] 
+0

非常感谢 – miik

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)] 

编辑:如果你有一个字符串列表(而不是字符串),就像@DSM建议,那么你必须修改它:

a = ['(111,11,12)','(12,34,56)'] 
[ast.literal_eval(b) for b in a] 
# [(111, 11, 12), (12, 34, 56)] 
+1

的OP似乎有一个列表字符串,而不是字符串(修改是微不足道的,当然。) – DSM

+0

EVAL是一件坏事mkay – Goranek

+2

@Goranek'ast.literal_eval'是内置'eval'不同 - 它是完全安全的使用,甚至当处理来自不受信任来源的数据。有关更多信息,请参阅http://docs.python.org/2/library/ast.html#ast-helpers。 – RocketDonkey

-2

您可以将字符串转换为int与INT()关键字:

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 

但是你给的例子似乎表明要对整个元组,而不是一个整数做到这一点。如果是这样,你可以使用内置的eval函数:

>>> eval('(111,111)') 
(111, 111) 
+0

是啊是这样的话 – miik

+0

-1:你的回答是最有帮助的OP的问题,请不要暗示可怕的EVAL。 – Abhijit

+0

为什么eval恐惧? –

0

通过阅读你的问题,我看你有一个字符串列表:

l = ['(111,11,12)','(12,34,56)'] 

并且您想将其转换为数字列表...

# 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 

对不起,列表理解解析,如果你是新的,看起来很奇怪,但是一个非常常见的Python成语,你应该熟悉它。

0

玩得开心!

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 

样品测试:

>>>s = "['(111,11,12)','(12,34,56)']" 
>>>a=customIntparser(s) 
>>> a 
# [(111, 11, 12), (12, 34, 56)] 
>a[0][1] 
# 11