【问题标题】:How can I set up a format check in python 3 if i want the data input by user to be of a particular format?如果我希望用户输入的数据具有特定格式,如何在 python 3 中设置格式检查?
【发布时间】:2016-09-09 03:17:28
【问题描述】:

所以基本上我想提示用户输入,这个输入应该遵循严格的顺序,即“一个大写字母后跟 2 个小写字母后跟 3 个数字或整数”的顺序 但是我写的代码给出了一个错误,这个错误只有在输入正确的格式时才会发生,否则在运行它时不会出错。我做错了什么,如何才能做到这一点? (附屏幕)enter image description here

enter image description here

【问题讨论】:

    标签: python python-2.7 validation python-3.x error-handling


    【解决方案1】:

    这正是正则表达式的用途

    ^[A-Z][a-z]{2}\d{3}$
    


    Python 实现:

    while 1:
        inputString = input()
        if re.match(r"^[A-Z][a-z]{2}\d{3}$", inputString):
            print("Input accepted")
            break
        else:
            print("Bad input, please try again")
    


    输出:

    Aa123      #missing one lowercase
    Bad input, please try again
    Aaa22      #missing one integer
    Bad input, please try again
    aaa123     #missing one capital
    Bad input, please try again
    Aaa123     # 1 capital, 2 lower, 3 integers
    Input accepted
    


    正则表达式的工作原理

    $ ---------> 在字符串的开头断言位置
    [A-Z] -----> 匹配一个大写字母
    [a-z]{2} --> 匹配两个小写字母
    \d{3} -----> 匹配 3 个数字
    $ ---------> 在字符串末尾断言位置

    【讨论】:

      【解决方案2】:

      在整数部分的验证中,您将其转换为整数并尝试对其进行字符串方法调用。尽量保持简单

      userID[3:5].isdigit()
      

      就够了。但是进行此验证的最佳方法是使用正则表达式。而且我觉得您还需要检查字符串的长度:

      def ValidateUserID(u):
          result = False
          if u[0] == u[0].upper() and u[1:2] == u[1:2].lower() and u[3:5].isdigit() and len(u) == 6:
              result = True
          return result
      

      希望对您有所帮助。快乐编码:)

      【讨论】:

      • 那么“.isdigit()”函数会检查字符串中的数字而不是整数值吗?非常感谢你,这帮助了很多:)
      • 是的@HogRider123 这就是给你造成问题的原因! :) 快乐的编码伙伴! :)
      • 这里还有一个简单的问题。如果我想使用函数名称“ValidateUserID”为所有这些代码定义一个函数,并根据结果获得真或假。你能告诉我如何为此修改我的代码吗?谢谢@san
      • @HogRider123 在代码中进行了编辑..请检查!! :)
      猜你喜欢
      • 2020-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多