如何在int中转换任何数字字符串值?

2024-09-25 08:36:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将0x12301236#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'

我觉得有点复杂。有什么内置方法吗?你知道吗


Tags: 方法rereturniffoovaluedef整数
3条回答

int就可以了,当您将0作为第二个参数传递时:

   int('0x123', 0)
=> 291
   int('0o12', 0)
=> 10

如果您想支持注释,str.partition是我能想到的最简单的方法:

   int('36#foo'.partition('#')[0], 0)
=> 36

是的,您可以使用ast.literal_eval。你知道吗

>>> import ast
>>> ast.literal_eval("0x123")
291
>>> ast.literal_eval("012")
10
>>> ast.literal_eval("36#foo")
36

但是,请注意literal_eval("012")只适用于2.7及更低版本,因为3.x不再支持这种八进制文字样式。但这是可行的:

>>> ast.literal_eval("0o12")
10

不带正则表达式的解决方案:

def convert (s):
    if s.lower().startswith('0x'):
        s = '16#' + s[2:]
    elif s.startswith('0'):
        s = '8#' + s[1:]
    elif '#' not in s:
        s = '10#' + s
    base, num = s.split('#', 1)
    return int(num, int(base))
>>> testcases = [('0x123', 291), ('012', 10), ('36#foo', 20328)]
>>> for s, n in testcases:
        print(s, n, n == convert(s))

0x123 291 True
012 10 True
36#foo 20328 True

相关问题 更多 >