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构造函数完全相同。
到目前为止,我拥有的最好的版本,非常难看,很难扩展到各种可用的浮点格式:
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
功能,为什么不直接使用它呢?E、 g.在我的Mac上在Linux、Windows等操作系统中,相同的代码应该可以工作,但是如果您检查
whereislib
,您将看到不同的路径(只有在真正的、非常特殊的安装中,如果此代码找不到C运行时库)。如果你想避免直接使用C库,我想你可以获取相关的前缀,例如使用re,比如
r'\s*([+-]?\d+)'
,然后尝试int
。相关问题 更多 >
编程相关推荐