Python 相当于 atoi/atof

标签 python

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

最佳答案

如果您非常热衷于获得 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

关于Python 相当于 atoi/atof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1665511/

相关文章:

python - Spark 读取 BigQuery 外部表

python - 在 jira-python 中访问工作日志中的特定信息

python - 如何在退出程序之前计算一定的秒数

python - 否定 python 中的自定义单元测试

python - listAPI View 中以十为基数的int()的文字无效 djangorest框架

python - 如何在python flask中使用Delete方法

python - 转置和扩展数据

python - 应用引擎 : uncaught application failure

python - Python 中的这种赋值叫什么? a = b = 真

python - 向 Python 字典键添加前缀的最有效方法