如何检查用户的字符串输入是否为数字(例如,-1
,0
,1
等)?
user_input = input("Enter something:")
if type(user_input) == int:
print("Is a number")
else:
print("Not a number")
由于 input
总是返回一个字符串,因此上述方法不起作用。
尝试将其转换为整数,如果失败则退出。
try:
val = int(userInput)
except ValueError:
print("That's not an int!")
请查看官方教程中的异常处理部分。
val = int(str(userInput))
。 - maxkoryukovint(True) == 1
和 int(False) == 0
。 - Loïc Faure-Lacroix显然,这种方法对于负数不起作用,但对于正数有效。
使用isdigit()
if userinput.isdigit():
#do stuff
isdecimal
而不是 isdigit
,因为 isdigit
是一种不安全的测试方法,它会将像 Unicode 2 的幂,² 等字符识别为数字,但无法转换为整数。 - Dave Rove使用方法isnumeric()
可以完成此任务:
>>>a = '123'
>>>a.isnumeric()
True
但请记住:
>>>a = '-1'
>>>a.isnumeric()
False
isnumeric()
函数在字符串中所有字符都是数字字符且至少有一个字符时返回True
。
因此,负数不被接受。
"123456".isnumeric()
)会产生AttributeError: 'str' object has no attribute 'isnumeric'
错误,而U"12345".numeric()
则为True
。 - perlykinga = '\U0001f10a'
。a.isnumeric()
为 True,但 int(a)
会引发 ValueError 异常。 - Artyer'3.3'.isnumeric()
的结果是 False
。 - Deqing对于 Python 3,下面的代码将有效。
userInput = 0
while True:
try:
userInput = int(input("Enter something: "))
except ValueError:
print("Not an integer!")
continue
else:
print("Yes an integer!")
break
编辑后: 您还可以使用以下代码来查找数字或负数
import re
num_format = re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$")
isnumber = re.match(num_format,givennumber)
if isnumber:
print "given string is number"
您也可以根据特定要求更改格式。我有点晚看到了这篇文章,但希望它能帮助其他正在寻找答案的人:). 如果给定的代码有任何错误,请告诉我。
user_input = ''
while user_input is not int:
try:
user_input = int(input('Enter a number: '))
break
except ValueError:
print('Please enter a valid number: ')
print('You entered {}'.format(user_input))
a = ''
while a.isdigit() == False:
a = input('Enter a number: ')
print('You entered {}'.format(a))
这个功能可以用来检查输入是否是正整数且在指定的范围内。
def checkIntValue():
'''Works fine for check if an **input** is
a positive Integer AND in a specific range'''
maxValue = 20
while True:
try:
intTarget = int(input('Your number ?'))
except ValueError:
continue
else:
if intTarget < 1 or intTarget > maxValue:
continue
else:
return (intTarget)
自然数:[0, 1, 2 ... ∞]
Python 2
it_is = unicode(user_input).isnumeric()
Python 3
it_is = str(user_input).isnumeric()
整数: [-∞, .., -2, -1, 0, 1, 2, ∞]
try:
int(user_input)
it_is = True
except ValueError:
it_is = False
浮点数: [-∞, .., -2, -1.0...1, -1, -0.0...1, 0, 0.0...1, ..., 1, 1.0...1, ..., ∞]
该内容介绍了一个包括负无穷、负数、零、正数和正无穷的浮点数范围。try:
float(user_input)
it_is = True
except ValueError:
it_is = False
最优雅的解决方案已经提出。
a = 123
bool_a = a.isnumeric()
很遗憾,它既不能用于负整数,也不能用于一般的浮点数a。如果您的目的是检查'a'是否是超出整数范围的通用数字,我建议使用以下方法,它适用于所有类型的浮点数和整数 :). 这是测试:
def isanumber(a):
try:
float(repr(a))
bool_a = True
except:
bool_a = False
return bool_a
a = 1 # Integer
isanumber(a)
>>> True
a = -2.5982347892 # General float
isanumber(a)
>>> True
a = '1' # Actually a string
isanumber(a)
>>> False
float
而不是bool
。 - Martin Tournoijimport re
num_format = re.compile(r'^\-?[1-9][0-9]*\.?[0-9]*')
然后你可以使用match()、findall()等方法对这个正则表达式进行操作。
num_format = re.compile(r'^\-?[1-9]+\.?[0-9]*')
? - skvalen
input
函数始终返回字符串。请参阅:http://docs.python.org/release/3.1.3/library/functions.html#input - Daniel DiPaoloeval(user_input)
的类型是整数,那么这个代码可能会起作用。 - R__raki__