我想知道是否有更容易的方法来做到这一点?
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)
答案 0 :(得分:5)
使用异常处理;请求原谅而不是许可:
try:
how_much = int(next)
except ValueError:
# handle the conversion failing; pass means 'ignore'
pass
答案 1 :(得分:0)
如果由于某种原因你不想使用异常处理并且想要使用正则表达式:
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,要么就是你我会描述一切。