Python 相当于 atoi / atof

新手上路,请多包涵

Python 喜欢引发异常,这通常很棒。但是我正面临一些我迫切希望使用 C 的 atoi / atof 语义转换为整数的字符串——例如“3 of 12”、“3/12”、“3 / 12”的 atoi 都应该变成 3; atof(“3.14 秒”) 应该变成 3.14; atoi(” -99 score”) 应该变成 -99。 Python 当然有 atoi 和 atof 函数,它们的行为与 atoi 和 atof 完全不同,而与 Python 自己的 int 和 float 构造函数完全一样。

到目前为止我拥有的最好的,这真的很丑陋并且很难扩展到可用的各种浮动格式:

 value = 1
s = str(s).strip()
if s.startswith("-"):
    value = -1
    s = s[1:]
elif s.startswith("+"):
    s = s[1:]
try:
    mul = int("".join(itertools.takewhile(str.isdigit, s)))
except (TypeError, ValueError, AttributeError):
    mul = 0
return mul * value

原文由 user79758 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 588
2 个回答

使用正则表达式执行此操作非常简单:

 >>> import re
>>> p = re.compile(r'[^\d-]*(-?[\d]+(\.[\d]*)?([eE][+-]?[\d]+)?)')
>>> def test(seq):
        for s in seq:
            m = p.match(s)
            if m:
                result = m.groups()[0]
                if "." in result or "e" in result or "E" in result:
                    print "{0} -> {1}".format(s, float(result))
                else:
                    print '"{0}" -> {1}'.format(s, int(result))
            else:
                print s, "no match"

>>> test(s)
"1 0" -> 1
"3 of 12" -> 3
"3 1/2" -> 3
"3/12" -> 3
3.15 seconds -> 3.15
3.0E+102 -> 3e+102
"what about 2?" -> 2
"what about -2?" -> -2
2.10a -> 2.1

原文由 Robert Rossney 发布,翻译遵循 CC BY-SA 2.5 许可协议

如果您非常热衷于获得 c 的功能 atoi ,为什么不直接使用它呢?例如,在我的 Mac 上,

 >>> import ctypes, ctypes.util
>>> whereislib = ctypes.util.find_library('c')
>>> whereislib
'/usr/lib/libc.dylib'
>>> clib = ctypes.cdll.LoadLibrary(whereislib)
>>> clib.atoi('-99foobar')
-99

在 Linux、Windows 等中,相同的代码应该可以工作,除了如果您检查 whereislib 会看到不同的路径(只有在真正非常特殊的安装上,此代码才能找到 C 运行时库) .

如果您热衷于避免直接使用 C 库,我想您可以获取相关前缀,例如使用诸如 r'\s*([+-]?\d+)' 类的 RE,然后尝试 int

原文由 Alex Martelli 发布,翻译遵循 CC BY-SA 2.5 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏