A UK Postcode Validation Script In Python

The below script takes the input of a UK postcode and ensures that it matches a valid format. I have handled the below formats:

  • X11XX
  • XX11XX
  • XX111XX

To do this, I use some regular expressions. Let’s look at one: “^[a-zA-Z]{1}[0-9]{2}[a-zA-Z]{2}”. Here:

  1. The beginning of the string (denoted with a ^) needs to be a letter. We need {1} occurence (i,.e. one letter).
  2. The next chunk needs to be numeric and there needs to be {2} of them.
  3. Finally, we require more letters, again, {2} occurences.

If the input value matches that pattern, we print ‘Matched!’.

import re
def validate_postcode(pc):
 pattern = 'not matched'
 #e.g. W27XX
 if len(pc.replace(" ", "")) == 5:
   pattern = re.compile("^[a-zA-Z]{1}[0-9]{2}[a-zA-Z]{2}")
 #e.g. TW27XX
 elif len(pc.replace(" ", "")) == 6:
   pattern = re.compile("^[a-zA-Z]{2}[0-9]{2}[a-zA-Z]{2}")
 #e.g. TW218FF
 elif len(pc.replace(" ", "")) == 7:
   pattern = re.compile("^[a-zA-Z]{2}[0-9]{3}[a-zA-Z]{2}")
 if pattern != 'not matched':
   if pattern.match(pc):