Search code examples
pythonfunctionfor-loopif-statementindices

how can i use a function to identify if zero is the first number in an alphanumeric string?


I'm trying to create a function that will identify if 0 is the first number in an alphanumeric sequence; for example, the function should evaluate to True if given the string "J02". I came up with a for loop that would work for inputs that are alphanumeric but not strictly alpha inputs.

x = "J02"
def not_starting_zero(m):
    zero_string = []
    for char in m:
        if char.isdigit() == True:
            zero_string.append(char)
            if m[len(m)-1] == char:
                if zero_string[0] == "0":
                    return False
                else:
                    return True
not_starting_zero(x)

I tried using an else statement that aligned with the indentation of the if char.isdigit() == True: ; but that would make the return of the function true if the first index of the string is a letter.


Solution

  • You could use a regular expression to find the first digit:

    import re
    
    def not_starting_zero(m):
        first_digit = re.search(r"([0-9])", m)
        if first_digit:
            return first_digit.group(0) == "0"
        else:
            return False
    

    Alternatively, you could use your looping version - I think you can just stop after you encounter the first digit:

    x = "J02"
    def not_starting_zero(m):
        for char in m:
            if char.isdigit() == True:
                if char == "0":
                    return True
                # otherwise, return False
                return False
    
        # if we get here, there weren't any numbers
        return False
    
    not_starting_zero(x)