Home > OS >  Is there a nice way to check a part of a string is made of letters and the other part is made of num
Is there a nice way to check a part of a string is made of letters and the other part is made of num

Time:10-12

  • I'm making a password checker, and one of the requirements is to check if the password could be a NY license plate (i.e. 4 letters then 3 numbers)

  • I did it like this:

def check_license(password):
    if len(password) == 7:
        if password[0].isalpha() and password[1].isalpha() and password[2].isalpha() and password[3].isdigit() and password[4].isdigit() and password[5].isdigit() and password[6].isdigit():
            print('License: -2')
            score -= 2

but I was wondering if there is a cleaner way to format that third line or just a faster way to do it.

CodePudding user response:

You could use regular expressions:

import re

def check_license(password):
    return bool(re.match(r'^[A-Za-z]{3}[0-9]{4}$', password))

CodePudding user response:

Maybe I'm missing something but I think you can just test the two parts of the string like this:

def is_license(s):
    return len(s) == 7 and s[:3].isalpha() and s[3:].isdigit()

for test in "abc1234", "ab12345", "ab123cd", "abc123a":
    print(is_license(test)) # True, False, False, False

This will include letters and numerals from other alphabets (e.g. is_license("和bc123٠") is True). To exclude these you could add the condition s.isascii().

  • Related