Skip to main content
 首页 » 编程设计

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

2025年05月04日20txw1958

我正在尝试编写一些东西来检查字符串是数字还是负数。如果它是一个数字(正数或负数),它将通过 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 

我能想到的唯一解决方案是一些单独的、复杂的语句系列,我可能将它们放在一个单独的函数中以使其看起来更好。如果有任何帮助,我将不胜感激!

请您参考如下方法:

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

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

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

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