首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python等同于atoi / atof

Python等同于atoi / atof
EN

Stack Overflow用户
提问于 2009-11-03 14:02:24
回答 6查看 33.9K关注 0票数 16

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

到目前为止,我拥有的最好的是,它真的很难看,很难扩展到各种可用的浮点格式:

代码语言:javascript
复制
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
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2009-11-06 00:12:20

使用正则表达式可以非常简单地做到这一点:

代码语言:javascript
复制
>>> 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
票数 4
EN

Stack Overflow用户

发布于 2009-11-03 14:15:55

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

代码语言:javascript
复制
>>> 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库,我想你可以获取相关的前缀,例如使用RE,比如r'\s*([+-]?\d+)',并在上面尝试int

票数 39
EN

Stack Overflow用户

发布于 2009-11-03 14:15:12

我认为迭代版本比递归版本更好。

代码语言:javascript
复制
# Iterative
def atof(s):
    s,_,_=s.partition(' ') # eg. this helps by trimming off at the first space
    while s:
        try:
            return float(s)
        except:
            s=s[:-1]
    return 0.0

# Recursive
def atof(s):
    try:
        return float(s)
    except:
        if not s:
            return 0.0
        return atof(s[:-1])


print atof("3 of 12")
print atof("3/12")
print atof("3 / 12")
print atof("3.14 seconds")
print atof("314e-2 seconds")
print atof("-99 score")
print atof("hello world")
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1665511

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档