如何在传递int()之前检查字符串是否为负数?

时间:2016-05-26 22:59:17

标签: python python-2.7

我正在尝试写一些检查字符串是数字还是负数的东西。如果它是一个数字(正数或负数),它将通过int()传递。不幸的是,当包含“ - ”时,isdigit()不会将其识别为数字。

这是我到目前为止所做的:

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

我能想到的唯一解决方案是一些单独的,错综复杂的语句系列,我可能会在一个单独的函数中松散,以使其看起来更好。我会感激任何帮助!

3 个答案:

答案 0 :(得分:5)

您可以先从左侧轻松删除字符,如下所示:

choice.lstrip('-+').isdigit()

然而,处理无效输入的异常可能会更好:

print x
while True:
    choice = raw_input("> ")
    try:
        y = int(choice)
        break
    except ValueError:
        print "Invalid input."
x += y

答案 1 :(得分:1)

不是检查是否可以将输入转换为数字,而是可以尝试转换,如果失败则执行其他操作:

choice = raw_input("> ")

try:
    y = int(choice)
    x += y
except ValueError:
    print "Invalid input."

答案 2 :(得分:1)

您可以使用float(str)解决此问题。如果它不是数字,则float应返回ValueError。如果您只处理整数,则可以使用int(str)

所以不要做

if choise.isdigit():
   #operation
else:
   #operation

你可以尝试

try:
    x = float(raw_input)
except ValueError:
    print ("What you entered is not a number")

随意用float替换int,告诉我它是否有效!我自己没有测试过。

编辑:我刚刚在Python的文档中看到了这一点(2.7.11)here

相关问题