如何在python中将字符串转换为int 说我有这个阵列
['(111,11,12)','(12,34,56)'] to [(111,11,12),(12,34,56)]
感谢任何帮助
答案 0 :(得分: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 :(得分: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]
答案 2 :(得分: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习语,你应该熟悉它。
答案 3 :(得分: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
答案 4 :(得分:-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)