Hi all was wondering how I make a program to check a string so that it only contains 2 or 3 numbers and 4 letters.
Example
string = input("Please enter a string: ") #example string would be HY21 4KK
if
string contains 2-3 characters
string contains 4 letters
print("This is valid")
else
Print("This is invalid")
the simpler the better, because im really new to programming
>Solution :
I would simply loop through all letters, sum how many there are, and the same for all digits, and then check if it matches your conditions, something like this:
import string
# string.ascii_lowercase is "abdcdef..."
# string.ascii_uppercase is "ABCDEF..."
# so string.ascii_lowercase + string.ascii_uppercase will be all lowercase letter, and then all uppercase letters.
# string.digits is "01234567890"
e = input("Please enter a string: ")
# Here we will sum the number of appearances of every letter, lower case or upper case, in the English alphabet
# to get the total number of letters in e:
letter_count = sum(e.count(i) for i in string.ascii_lowercase + string.ascii_uppercase)
# Same here except with all digits:
digit_count = sum(e.count(i) for i in string.digits)
if digit_count in [2, 3] and letter_count == 4:
print("This is valid")
else:
print("This is invalid")