Reputation: 49
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
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 lineFor 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
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
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