我想将0x123
、012
或36#foo
转换为整数。你知道吗
为此,我写道:
def str2int(s):
if re.findall('(?i)^0x',s):
return int(s, 16)
if re.findall('^(?i)0',s):
return int(s, 8)
m = re.findall('(?i)^(\d+)\#([0-9a-z]+)',s)
if m:
return int(m[0][1], m[0][0])
raise AssertionError, 'Unknown value'
我觉得有点复杂。有什么内置方法吗?你知道吗
int
就可以了,当您将0
作为第二个参数传递时:如果您想支持注释,
str.partition
是我能想到的最简单的方法:是的,您可以使用
ast.literal_eval
。你知道吗但是,请注意
literal_eval("012")
只适用于2.7及更低版本,因为3.x不再支持这种八进制文字样式。但这是可行的:不带正则表达式的解决方案:
相关问题 更多 >
编程相关推荐