我正在尝试验证用户的输入。我只希望用户能够输入正整数或负整数。所有其他输入(即任何带字母的输入)都应该被拒绝
我现在有下面的代码,但是我收到了错误。我假设它与数据类型有关,但我不确定如何解决这个问题。
import re
number =input("Please enter a number: ")
number=int(number)
while not re.match("^[0-9 \-]+$", number):
print ("Error! Make sure you only use numbers")
number = input("Please enter a number: ")
print("You picked number "+ number)
答案 0 :(得分:6)
如果您关心的是输入是有效的数字文字,请不要使用正则表达式。 int
将正确解析字符串或引发异常。
while True:
s = input("Please enter a number: ")
try:
n = int(s)
break
except ValueError:
print("Error! Make sure you only use numbers")
print("You picked number " + n)
答案 1 :(得分:1)
正则表达式需要字符串作为输入,而不是数字。因此,您不必将字符串强制转换为数字,并且可以省略number=int(number)
。
这是working demo:
number = "2"
if not re.match("^[0-9 -]+$", number):
print ("Error! Make sure you only use numbers")
print("You picked number "+ number)
答案 2 :(得分:0)
import re
while True:
number =input("Please enter a number: ")
# number=int(number) -- This raise an error, for regexp you need use "str"
#while not re.match("^[0-9 \-]+$", number):
# in [0-9 \-] after 9 you use whitespace
# Also in [0-9 \-] if minus at the and, not need use backslash
if re.match("-?\d+$", number) : # minus may be only in first position
break
print ("Error! Make sure you only use numbers")
# deleted number = input("Please enter a number: ")
print("You picked number "+ number)
答案 3 :(得分:0)
answer = input(" ")#asks the user for an answer
ansnum = re.match("[0-9 \-]",answer)#checks to see if answer only contains numbers
while not ansnum: #whilst the answer does not contain numbers do....
answer = input("Enter numbers as your answer: ")#asks the user for a valid answer
ansnum = re.match("[0-9 \-]",answer)#checks to see if the answer contains numbers