将 Python 输入字符串限制为特定字符和长度

发布于 2024-12-25 10:49:04 字数 267 浏览 1 评论 0原文

我刚刚开始学习我的第一种真正的编程语言——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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

怎樣才叫好 2025-01-01 10:49:04

问题 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

Question 1: Restrict to certain characters

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()

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:

input_str = raw_input("Please provide some info: ")
if len(input_str) > 15:
    print "Error! Only 15 characters allowed!"
    sys.exit()

Or both in one:

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
断舍离 2025-01-01 10:49:04

正则表达式还可以限制字符数。

r = re.compile("^[a-z]{1,15}$")

为您提供一个正则表达式,仅当输入完全是小写 ASCII 字母且长度为 1 到 15 个字符时才匹配。

Regexes can also limit the number of characters.

r = re.compile("^[a-z]{1,15}$")

gives you a regex that only matches if the input is entirely lowercase ASCII letters and 1 to 15 characters long.

梦萦几度 2025-01-01 10:49:04

我们可以在这里使用 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)

We can use assert here.

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

You can build a wrapper around input function.

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)
怀念你的温柔 2025-01-01 10:49:04
if any( [ i>'z' or i<'a' for i in raw_input]):
    print "Error: Contains illegal characters"
elif len(raw_input)>15:
    print "Very long string"
if any( [ i>'z' or i<'a' for i in raw_input]):
    print "Error: Contains illegal characters"
elif len(raw_input)>15:
    print "Very long string"
小女人ら 2025-01-01 10:49:04

也许您可以通过导入字符串来验证字符串类型来获取它们:

def enter_sentence():
condition = False
while not condition:
    sentence = input('Enter a sentence please: ').lower()
    lower_check_list = list(string.ascii_lowercase + ' ')
    for letter in sentence:
        if letter not in lower_check_list:
            print('Enter only a letter characters.Try again')
            break
    else:
        if len(sentence) > 15:
            print('The maximum number of characters is 14. Try again')
        else:
            condition = True

return 'Your sentence has been verified and complies'



print(enter_sentence())

possibly you can get them with importing string to verify the string type:

def enter_sentence():
condition = False
while not condition:
    sentence = input('Enter a sentence please: ').lower()
    lower_check_list = list(string.ascii_lowercase + ' ')
    for letter in sentence:
        if letter not in lower_check_list:
            print('Enter only a letter characters.Try again')
            break
    else:
        if len(sentence) > 15:
            print('The maximum number of characters is 14. Try again')
        else:
            condition = True

return 'Your sentence has been verified and complies'



print(enter_sentence())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文