限制Python输入字符串为特定字符和长度
我刚开始学习我的第一个真正的编程语言,Python。我想知道如何限制用户在raw_input
中输入特定的字符和长度。例如,如果用户输入的字符串包含除了字母a-z
以外的任何东西,我想显示一个错误信息;如果用户输入的内容超过15个字符,我也想显示一个错误信息。
第一个问题听起来像是我可以用正则表达式来解决,我对正则表达式有一点了解,因为我在Javascript中用过,但我不太确定在Python中该怎么用。至于第二个问题,我也不知道该怎么处理。有人能帮忙吗?
5 个回答
3
我们可以在这里使用 assert
。
def custom_input(inp_str: str):
try:
assert len(inp_str) <= 15, print("More than 15 characters present")
assert all("a" <= i <= "z" for i in inp_str), print(
'Characters other than "a"-"z" are found'
)
return inp_str
except Exception as e:
pass
custom_input('abcd')
#abcd
custom_input('abc d')
#Characters other than "a"-"z" are found
custom_input('abcdefghijklmnopqrst')
#More than 15 characters present
你可以在 input
函数外面包裹一层。
def input_wrapper(input_func):
def wrapper(*args, **kwargs):
inp = input_func(*args, **kwargs)
if len(inp) > 15:
raise ValueError("Input length longer than 15")
elif not inp.isalpha():
raise ValueError("Non-alphabets found")
return inp
return wrapper
custom_input = input_wrapper(input)
15
正则表达式(Regex)也可以限制字符的数量。
r = re.compile("^[a-z]{1,15}$")
这个正则表达式只会匹配那些完全由小写字母组成,并且长度在1到15个字符之间的输入。
21
问题 1:限制特定字符
你说得对,这个问题用正则表达式来解决非常简单:
import re
input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
print "Error! Only letters a-z allowed!"
sys.exit()
问题 2:限制特定长度
正如Tim正确提到的,你可以通过调整第一个例子中的正则表达式,只允许特定数量的字母。你也可以像这样手动检查长度:
input_str = raw_input("Please provide some info: ")
if len(input_str) > 15:
print "Error! Only 15 characters allowed!"
sys.exit()
或者把两者结合起来:
import re
input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
print "Error! Only letters a-z allowed!"
sys.exit()
elif len(input_str) > 15:
print "Error! Only 15 characters allowed!"
sys.exit()
print "Your input was:", input_str