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

标签 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!")

最佳答案

我不确定为什么会失败,但我猜测更 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

关于Python2,检查字符串是否只包含数字,与 x.isdigit() 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43419257/

相关文章:

python - 如何将主成分分析的结果映射回输入模型的实际特征?

python - 如何正确测量jupyter中单元格的执行时间?

python - 保存 NLTK HMM 时出错

c# - 在 C# 中的字符串列表中查找字符串

python - Pyspark RDD .filter() 带通配符

python - 从同名脚本导入 Python 包

java - Java中如何高效地将二进制字符串转换为二进制字节数组?

C++ 标准 :string memory model

c# - 选择字符串中的上一个和下一个单词

java - 从 java 字符串生成 SOAP 消息