如何在通过 int() 之前检查字符串是否为负数? [英] How do I check if a string is a negative number before passing it through int()?
问题描述
我正在尝试编写一些东西来检查字符串是数字还是负数.如果它是一个数字(正数或负数),它将通过 int() 传递.不幸的是,当包含-"时,isdigit() 不会将其识别为数字.
I'm trying to write something that checks if a string is a number or a negative. If it's a number (positive or negative) it will passed through int(). Unfortunately isdigit() won't recognize it as a number when "-" is included.
这是我目前所拥有的:
def contestTest():
# Neutral point for struggle/tug of war/contest
x = 0
while -5 < x < 5:
print "Type desired amount of damage."
print x
choice = raw_input("> ")
if choice.isdigit():
y = int(choice)
x += y
else:
print "Invalid input."
if -5 >= x:
print "x is low. Loss."
print x
elif 5 <= x:
print "x is high. Win."
print x
else:
print "Something went wrong."
print x
我能想到的唯一解决方案是一些单独的、令人费解的语句系列,我可能会将它们放在一个单独的函数中以使其看起来更好.如有任何帮助,我将不胜感激!
The only solution I can think of is some separate, convoluted series of statements that I might squirrel away in a separate function to make it look nicer. I'd be grateful for any help!
推荐答案
您可以轻松地先删除左边的字符,如下所示:
You can easily remove the characters from the left first, like so:
choice.lstrip('-+').isdigit()
然而,处理来自无效输入的异常可能会更好:
However it would probably be better to handle exceptions from invalid input instead:
print x
while True:
choice = raw_input("> ")
try:
y = int(choice)
break
except ValueError:
print "Invalid input."
x += y
这篇关于如何在通过 int() 之前检查字符串是否为负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!