如何检查用户输入的字符串是否为数字(例如-1、0、1等)?
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")上面的方法不起作用,因为input总是返回一个字符串。
发布于 2011-03-25 03:53:48
只需尝试将其转换为int类型,然后在不起作用时退出。
try:
val = int(userInput)
except ValueError:
print("That's not an int!")请参见Handling Exceptions https://docs.python.org/3/tutorial/errors.html#handling-exceptions
发布于 2011-03-25 03:54:34
显然,这不适用于负值,但适用于正数。
使用isdigit()
if userinput.isdigit():
#do stuff发布于 2015-09-06 03:16:42
方法isnumeric()将完成这项工作(Documentation for python3.x):
>>>a = '123'
>>>a.isnumeric()
True但请记住:
>>>a = '-1'
>>>a.isnumeric()
False如果字符串中的所有字符都是数字字符,并且至少有一个字符,则isnumeric()返回True。
所以负数是不被接受的。
https://stackoverflow.com/questions/5424716
复制相似问题