Python2,检查字符串是否只包含数字,与x.isdigit()混淆

时间:2017-04-14 21:05:05

标签: python string

看了How do you check in python whether a string contains only numbers?后,我知道string.isdigit()是一种有效的方法来测试一个字符串是否只包含数字而不是其他内容。我使用的是Python 2.7。

但是,当我尝试在下面的代码中使用它时,当我输入任何数字和非数字的混合时,我的程序崩溃时出现“带有基数为10的int()的无效文字”错误,例如“fsd7sfd”或类似的。 (该代码适用于仅限数字的字符串或仅限字母的字符串。)

我不明白这是怎么回事,因为据我所知,“how_much = int(choice)”的赋值永远不会发生除非字符串只包含数字第一个地方,当choice.isdigit()为True时。

有人能帮助我理解我所缺少的东西吗?

作为旁注,“打印”测试“”行似乎也没有在错误之前得到处理,这增加了我的困惑。

(我正在尝试从https://learnpythonthehardway.org/book/ex35.html改进“gold_room()”函数,其余代码可供参考。)

错误:

This room is full of gold.  How much do you take?
> sdfgsd8sd 
Traceback (most recent call last):
File "ex35.py", line 79, in <module>
start()
File "ex35.py", line 71, in start
bear_room()
File "ex35.py", line 36, in bear_room
gold_room()
File "ex35.py", line 9, in gold_room
how_much = int(choice)
ValueError: invalid literal for int() with base 10: 'sdfgsd8sd'

代码:

def gold_room():
    print "This room is full of gold.  How much do you take?"

    choice = raw_input("> ")

    print "test" 

    if choice.isdigit() == False:
        dead("Man, learn to type a number.")

    else:
        how_much = int(choice)


    if how_much < 50:
        print "Nice, you're not greedy, you win!"
        exit(0)

    else:
        dead("You greedy bastard!")

2 个答案:

答案 0 :(得分:1)

我不确定为什么会失败,但在我的猜测中,更多的pythonic方式是通过try except语句来捕获值错误:

try:
    #The following will fail with an non-numeric input
    how_much = int(choice)
except ValueError:
    dead('Man, learn to type a number.')
#Note that the else statement is not necessary as it will never execute anyway

答案 1 :(得分:0)

你需要在脚本中使用死函数

def dead(message):
    print(message)
choice = raw_input("> ")
print "test"
if choice.isdigit() == False:
    dead("Man learn to type a number")