【问题标题】:Limiting Python input strings to certain characters and lengths将 Python 输入字符串限制为某些字符和长度
【发布时间】:2012-01-06 17:21:56
【问题描述】:

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

第一个似乎是我可以用正则表达式做的事情,我知道一点,因为我在 Javascript 中使用过它们,但我不确定如何在 Python 中使用它们。第二个,我不知道如何处理它。有人可以帮忙吗?

【问题讨论】:

    标签: python string limit user-input


    【解决方案1】:

    问题 1:仅限某些字符

    你是对的,这很容易用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:限制一定长度

    正如蒂姆正确提到的那样,您可以通过调整第一个示例中的正则表达式来只允许一定数量的字母来做到这一点。您也可以像这样手动检查长度:

    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
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        【解决方案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)
        

        【讨论】:

          【解决方案4】:
          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"
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-04-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-05-24
            • 1970-01-01
            相关资源
            最近更新 更多