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.
CodePudding user response:
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)
CodePudding user response:
I suppose you could use regex and extract the numeric digits into a list. Something like this -
import re
def not_starting_zero(m):
numbers = re.findall('[0-9]', m)
if numbers[0] == '0':
return false
else
return true
CodePudding user response:
I'm assuming you mean the first digit you find is 0 (because otherwise it should return False for "J02" because 02 is the first number)
x = "J02"
def not_starting_zero(m):
for char in m:
if char.isdigit() == True:
if char == "0":
return True
else:
return False
return False
not_starting_zero(x)
This works because once return is executed in a function the rest of the function is not executed. Hope this clears up your doubt.
You don't need to make an array of the digits because you only need to check the first digit in the string; if its a 0 then return True else return False.
CodePudding user response:
Below code can find if 0 is the first number in alphanumeric string.
import regex as re
x = "J02"
True if re.findall('[0-9]', x)[0] == '0' else False
Output:
True