Reputation: 33
I need to check if my input is all caps and numbers, it must also contain "A1" and be a multiple of 4.
def valid_product_code(string):
#A1 must be in string
if "A1" in string:
val = True
#String must be a multiple of 4
if len(string) % 4 == 0:
val = True
#Must only have capitals or numbers
if (char.isdigit() or char.islower() for char in string):
val=True
else:
val = False
return val
What am I doing wrong? When I test it, it only returns True
Upvotes: 0
Views: 488
Reputation: 802
Try this out, it uses some regex to check and make sure all letters are capitalized
import re
def valid_product_code(string):
# Regex pattern to check for all caps
pattern = '^[A-Z0-9]*$'
# Validation
valid = False
# Check for all caps
if re.search(pattern, string):
# Check for A1
if "A1" in string:
# Check for multiple of 4
if len(string) % 4 == 0:
valid = True
return valid
Regex is a great use case for something like this. You could also modify your function to automatically convert the string to upper case with string.upper(). Then you can return the capitalize string along with validation check with return string, valid. This would eliminate the need to check for capital letters all together.
Upvotes: 2
Reputation: 108
You need to add all keyword so it will check all of the characters, change the islower to isupper and you override the return value
def valid_product_code(string):
#A1 must be in string
if "A1" not in string:
return False
#String must be a multiple of 4
if len(string) % 4 != 0:
return False
#Must only have capitals or numbers
if not all(char.isdigit() or char.isupper() for char in string):
return False
return True
Upvotes: 2