如何检查字符串输入是否为数字?
问题描述:
如何检查用户的字符串输入是否为数字(例如-1
,0
,1
等)?
How do I check if a user's string input is a number (e.g. -1
, 0
, 1
, etc.)?
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
由于input
始终返回字符串,因此上述方法无效.
The above won't work since input
always returns a string.
答
简单地尝试将其转换为int,然后在不起作用时进行补救.
Simply try converting it to an int and then bailing out if it doesn't work.
try:
val = int(userInput)
except ValueError:
print("That's not an int!")