Eden Bendheim
Eden Bendheim

Reputation: 1

Is there a nice way to check a part of a string is made of letters and the other part is made of numbers in python

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. 3 letters then 4 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.

Upvotes: 0

Views: 70

Answers (2)

Stuart
Stuart

Reputation: 9858

Test the two slices 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().

Upvotes: 1

esqew
esqew

Reputation: 44699

You could use regular expressions:

import re

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

Upvotes: 4

Related Questions