Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you check a string so that it contains only certain amount of numbers and characters

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading