I have to validate that the string is either 4 or 6 digits. The string cannot contain any characters, only integers. Return true if it meets the condition else false.
I tried to create a list with acceptable digits and loop through the string and compare. If any part of the string is not in the acceptable list I will exit the loop and return false. If the running total is equal to 4 or 6 then it should be true. python code:
def validate(n):
count = 0
valid_list = list(range(10))
for digit in pin:
if digit not in valid_list:
return False
count += 1
I'm not sure why something like 1234 is being returned as False.
How about with regex?
import re
str="03506"
pattern="[0-9]{4,6}"
prog=re.compile(pattern)
result=prog.match(str)
if result:
return True
else:
return False
This matches digits that are between 4 and 6 characters long. If you mean you want to match those string that are 4 or 6 long, you can try
import re
str="03506"
pattern1="[0-9]{4}"
pattern2="[0-9]{6}"
if re.match(pattern1,str) or re.match(pattern2, str):
return True
else:
return False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With