【问题标题】:Checking if string contains a specific amount of letters and numbers检查字符串是否包含特定数量的字母和数字
【发布时间】:2021-10-27 20:30:12
【问题描述】:

如何检查给定的字符串/输入是否包含四个字母和三个数字?

def emne_validator(emne):
    if len(emne)==7 and emne[-3].isnumeric():
        print("Valid input")
    else:
        print("Invalid input")
    

【问题讨论】:

标签: python string


【解决方案1】:

您可以使用regex 查找和计数letternumber,如下所示:

>>> import re
>>> st = " I am 1234 a 56 nice #$%$"
>>> cntLttr = len(re.findall(r'[a-zA-Z]+', st))
>>> cntLttr
4
>>> cntNUm  = len(re.findall(r'\d+', st))
>>> cntNUm
2

# for more explanation
>>> re.findall(r'[a-zA-Z]+', st)
['I', 'am', 'a', 'nice']

>>> re.findall(r'\d+', st)
['1234', '56']

您可以使用.isdigit().isalpha(),但您需要.split(),如下所示:

>>> sum(lt.isdigit() for lt in st.split())
2

>>> sum(lt.isalpha() for lt in st.split())
4

>>> st.split()
['I', 'am', '1234', 'a', '56', 'nice', '#$%$']

【讨论】:

    【解决方案2】:

    这应该可行:

    from string import digits
    from string import ascii_letters
    
    def emne_validator(emne: str):
        digit_count = 0
        letter_count = 0
        for char in emne:
            if char in digits:
                digit_count += 1
            elif char in ascii_letters:
                letter_count += 1
        if letter_count == 4 and digit_count == 3:
            print("Valid input")
        else:
            print("Invalid input")
    
    emne_validator("0v3rfl0w")
    emne_validator("0v3rfl0")
    

    输出:

    Invalid input
    Valid input
    

    【讨论】:

      【解决方案3】:

      您还可以使用具有 2 个断言的单一模式,1 个仅用于 4 个单个字母 A-Za-z,一个仅用于 3 个单个数字。

      ^(?=(?:[^a-zA-Z\n]*[a-zA-Z]){4}[^a-zA-Z\n]*\Z)(?=(?:[^\d\n]*\d){3}[^\d\n]*\Z)
      
      • ^ 字符串开始
      • (?=(?:[^a-zA-Z\n]*[a-zA-Z]){4}[^a-zA-Z\n]*\Z) 在整行中断言 4 次单个字符 A-Z 或 a-z
      • (?=(?:[^\d\n]*\d){3}[^\d\n]*\Z)整行单个数字断言3次

      Regex demo | Python demo

      例如:

      import re
      
      strings = [
          "t1E2S3T",
          "t1E2S33"
      ]
      
      def emne_validator(emne):
          pattern = r"(?=(?:[^a-zA-Z\n]*[a-zA-Z]){4}[^a-zA-Z\n]*\Z)(?=(?:[^\d\n]*\d){3}[^\d\n]*\Z)"
          m = re.match(pattern, emne)
          return m is not None
      
      for txt in strings:
          result = emne_validator(txt)
          if result:
              print(f"Valid input for: {txt}")
          else:
              print(f"Invalid input for: {txt}")
      

      输出

      Valid input for: t1E2S3T
      Invalid input for: t1E2S33
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-04
        • 2021-10-01
        • 2012-02-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多