使用 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 否则您将分析所有内容。