繁体   English   中英

使用int(str)

[英]Use of int(str)

我想知道是否有更简单的方法来做到这一点?

if '0' in next or '1' in next or '2' in next or '3' in next or '4' in next or '5' in next or '6' in next or '7' in next or '8' in next or '9' in next:
        how_much = int(next)

使用异常处理; 要求宽恕而不是允许:

try:
    how_much = int(next)
except ValueError:
    # handle the conversion failing; pass means 'ignore'
    pass

如果由于某种原因您不想使用异常处理,而是想使用正则表达式:

re_is_int=re.compile('-?\d+$') #-? possible negative sign
                             #\d -> is digit.
                             #+ -> at least one. In this case, at least one digit.
                             #$ -> end of line.
                             #Not using '^' for start of line because I can just use re.match for that.
if re_is_int.match(next): #do rename this variable, you're shadowing the builtin next
                          #re.match only matches for start of line.
    how_much = int(next)

与Martijn的方法相比,我没有介绍这种方法。 我怀疑如果您的输入主要是数字,他的表现会更好,而如果我的输入大部分不是数字,我的表现会更好,但是坦率地说,如果您无论如何都要关心性能,则要么不会使用python,要么将分析所有内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM