I was just wondering how one would write a code that validates a string? For example a user inputs a postal code (string). i have to make sure it follows a L#L#L# format L-> represents a letter only and #-> represents only a number not decimal ...if not ask user to enter again
Asked
Active
Viewed 4,018 times
1
-
4Check out the [regex module](https://docs.python.org/3/library/re.html) – C.Nivs Apr 05 '19 at 18:07
1 Answers
1
String Methods more info
For your example you could slice the string with a step of 2 checking every other if it is a digit/letter:
.isdecimal
checks for characters that make up base-10 numbers systems (0-9).
.isalpha
checks for letters (A-Z)
test_good = 'L5L5L5'
test_bad = 'LLLLLL'
def check_string(test):
if test[0::2].isalpha() and test[1::2].isdecimal():
return True
else:
return False
Test it out:
check_string(test_good)
>>>True
Negative test:
check_string(test_bad)
>>>False
Regex does pattern matching operations and really a lot more. In the example below I compiled the pattern ahead of time so that it looks clean and can be reused if needed.
I also use re.fullmatch()
which requires the entire provided string match, not just one part of it. On its own it will return None
or the match object, so I check to see if it exists (meaning it matched) and return True or if not (None) return False.
import re
def match(test):
re_pattern = re.compile('[A-Z][0-9][A-Z][0-9][A-Z][0-9]')
if re.fullmatch(re_pattern, test):
return True
else:
return False

MyNameIsCaleb
- 4,409
- 1
- 13
- 31