Sondre
Sondre

Reputation: 49

Checking if string contains a specific amount of letters and numbers

How can i check if a given string/input has four letters and 3 numbers in it?

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

Upvotes: 2

Views: 458

Answers (3)

The fourth bird
The fourth bird

Reputation: 163217

You can also use a single pattern with 2 assertions, 1 for only 4 single letters A-Za-z and one for only 3 single digits.

^(?=(?:[^a-zA-Z\n]*[a-zA-Z]){4}[^a-zA-Z\n]*\Z)(?=(?:[^\d\n]*\d){3}[^\d\n]*\Z)
  • ^ Start of string
  • (?=(?:[^a-zA-Z\n]*[a-zA-Z]){4}[^a-zA-Z\n]*\Z) Assert 4 times a single char A-Z or a-z in the whole line
  • (?=(?:[^\d\n]*\d){3}[^\d\n]*\Z) Assert 3 times a single digit in the whole line

Regex demo | Python demo

For example:

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}")

Output

Valid input for: t1E2S3T
Invalid input for: t1E2S33

Upvotes: 0

I'mahdi
I'mahdi

Reputation: 24049

You can use regex and find and count letter and number like below:

>>> 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']

You can use .isdigit() and .isalpha() but you need .split() like below:

>>> 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', '#$%$']

Upvotes: 1

user8563312
user8563312

Reputation:

This should work:

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

Output:

Invalid input
Valid input

Upvotes: 0

Related Questions