在Python3中查找字符串是否为数字的更简单方法

2024-10-02 12:30:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编程很陌生。我试图找出如何检查用户输入(存储为字符串)是否为整数且不包含字母。我在论坛上查了一些资料,最后得出这样的结论:

while 1:

#Set variables
    age=input("Enter age: ")
    correctvalue=1

#Check if user input COULD be changed to an integer. If not, changed variable to 0
    try:
        variable = int(age)
    except ValueError:
        correctvalue=0
        print("thats no age!")

#If value left at 1, prints age and breaks out of loop.
#If changed, gives instructions to user and repeats loop.
    if correctvalue == 1:
        age=int(age)
        print ("Your age is: " + str(age))
        break
    else:
        print ("Please enter only numbers and without decimal point")

现在,这是如图所示的工作方式,我想做什么(询问他们的年龄直到他们输入一个整数),然而对于这样一个简单的事情来说,这是相当长的。我试图找到一个,但我得到了太多的数据,我还不明白。在

有没有一个简单的方法,甚至是一个简单的函数来完成这个过程?在


Tags: andtoloopinputageif编程整数
3条回答

您可以根据需要删除不必要的correctvalue变量和breaking或{}-ing来缩短这段时间。在

while True:
    age=input("Enter age: ")    
    try:
        age = int(age)
    except ValueError:
        print("thats no age!")
        print ("Please enter only numbers and without decimal point")
    else:
        break

print ("Your age is: " + str(age))

使用isdigit()

"34".isdigit()
>>> "34".isdigit()
True
>>> "3.4".isdigit()
False
>>> 

所以像这样:

^{pr2}$

这适用于非负整数(即,没有符号标记):

variable = ''
while True:
    variable = input("Age: ")
    if variable.isdigit():
        break
    else:
        print("That's not an age!")
variable = int(variable)

其思想是不断循环,直到用户输入一个只包含数字的字符串(这就是^{}所做的)。在

相关问题 更多 >

    热门问题