将Python输入字符串限制为某些字符和长度 [英] Limiting Python input strings to certain characters and lengths

查看:2931
本文介绍了将Python输入字符串限制为某些字符和长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习我的第一种真正的编程语言Python.我想知道如何将raw_input中的用户输入限制为某些字符和特定长度.例如,如果用户输入的字符串中包含字母a-z以外的任何内容,我想显示一条错误消息,并且我想显示其中一个用户输入的字符超过15个.

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.

第一个似乎是我可以使用正则表达式做的事情,由于我已经在Java语言中使用过它们,所以我对它有所了解,但是我不确定如何在Python中使用它们.第二个,我不确定该如何处理.有人可以帮忙吗?

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?

推荐答案

问题1:仅限某些字符

您是对的,使用正则表达式很容易解决:

You are right, this is easy to solve with regular expressions:

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正确提到的那样,您可以通过调整第一个示例中的正则表达式以只允许一定数量的字母来做到这一点.您也可以像这样手动检查长度:

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:

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

这篇关于将Python输入字符串限制为某些字符和长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆