Detect numbers between letters in a string python

Viewed 105

I write a code to verify the license plates of cars and there are some conditions to achieve this purpose:

  • The first letter should not be 0
  • It shouldn't have any numbers between letters(AAA12 is ok, but AA2AAA is not.)
  • It should start with two letters
  • The count of letters must be between 2 - 6 letters
def is_valid(s):
    s = s.lower()
    if len(s) >= 2 and len(s) <= 6 and s[0] != 0 and s[0:2].isalpha():
        if s.isalpha():
            return True
        elif s.isalnum():
            for sq in s.split():
                for w in sq:
                    if w.isdigit():
                        x = sq.index(w)
                        try:
                            if s[w:].isalpha():
                                return False
                            else:
                                return True
    
                        except:
                            return True

So my code is doing most of these conditions in a right way, but when I enter e.g. HL23P2, I expect to get False but it returns True.

Why does it return False? because I can't have numbers between letters only it is allowed when its like e.g. HEL23.

But how can I detect numbers between letters?

3 Answers

I think, that this solution without regular expression would be ok:

def is_valid(s):
    meetNumber = False
    if len(s) >= 2 and len(s) <= 6 and s[0:2].isalpha():
        for i in range(2, len(s)):
            if s[i].isnumeric():
                meetNumber = True
            elif meetNumber == True:
                return False
        return True
    else:
        return False

print(is_valid(input()))

Try something like:

import re

def is_valid(s):
    return bool(re.search(r'^(?=.{2,6}$)[A-Z]{2,}\d*$', s))

print([is_valid(el) for el in ['AAA12', 'AA2AAA', 'HL23P2', 'HEL23']])

Prints:

[True, False, False, True]

The regular expression used means:

  • ^ - Start string;
  • (?=.{2,6}$) - Positive lookahead to match 2-6 characters exactly untill end-string anchor (accomodate your requirement of 2-6 characters total);
  • [A-Z]{2,} - 2+ uppercase alpha (accomodate your requirement to start with at least 2 alphachars);
  • \d* - 0+ digits (accomodate your requirement to have no numbers between characters but only possible at end);
  • $ - End-string anchor.

here is the correct answer:

def is_valid(s):
    if 2 <= len(s) <= 6 and s[0:2].isalpha() and s.isalnum():
        for item in s:
            if item.isdigit():
                pos = s.index(item)
                if s[pos:].isdigit() and int(item) != 0:
                    return True
                else:
                    return False

        return True
Related