将 Python 输入字符串限制为特定字符和长度
我刚刚开始学习我的第一种真正的编程语言——Python。我想知道如何将 raw_input
中的用户输入限制为特定字符和特定长度。例如,如果用户输入的字符串包含除字母 az
之外的任何内容,我想显示一条错误消息,并且我想显示其中一个用户输入超过 15 个字符。
第一个似乎是我可以用正则表达式做的事情,我对此有所了解,因为我在 Javascript 中使用过它们,但我不确定如何在 Python 中使用它们。第二个,我不知道如何处理它。有人可以帮忙吗?
I just started learning my first real programming language, Python. I'd like to know how to constrain user input in a raw_input
to certain characters and to a certain length. For example, I'd like to show an error message if the user inputs a string that contains anything except the letters a-z
, and I'd like to show one of the user inputs more than 15 characters.
The first one seems like something I could do with regular expressions, which I know a little of because I've used them in Javascript things, but I'm not sure how to use them in Python. The second one, I'm not sure how to approach it. Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
问题 1:限制某些字符
你是对的,使用 正则表达式:
问题 2:限制一定长度
正如 Tim 正确提到的,您可以通过调整第一个示例中的正则表达式以仅允许一定数量的字母来实现此目的。您还可以像这样手动检查长度:
或者两者合而为一:
Question 1: Restrict to certain characters
You are right, this is easy to solve with regular expressions:
Question 2: Restrict to certain length
As Tim mentioned correctly, you can do this by adapting the regular expression in the first example to only allow a certain number of letters. You can also manually check the length like this:
Or both in one:
正则表达式还可以限制字符数。
为您提供一个正则表达式,仅当输入完全是小写 ASCII 字母且长度为 1 到 15 个字符时才匹配。
Regexes can also limit the number of characters.
gives you a regex that only matches if the input is entirely lowercase ASCII letters and 1 to 15 characters long.
我们可以在这里使用
assert
。您可以围绕
input
函数构建一个包装器。We can use
assert
here.You can build a wrapper around
input
function.也许您可以通过导入字符串来验证字符串类型来获取它们:
possibly you can get them with importing string to verify the string type: