A python package for UK Postcodes validation and formatting.
Install using pip
:
pip install -U ukpocopy
To validate a postcode, you can use validate_postcode
function directly:
from ukpocopy.validators import validate_postcode
from ukpocopy.exceptions import PostcodeValidationError
# valid postcode
validate_postcode("SW1W 0NY") # returns True
# invalid postcode
try:
validate_postcode("0000 000") # raises some PostcodeValidationError exception
except PostcodeValidationError:
# handle validation errors
pass
Postcode validations also happens during UKPostcode
instantiation:
from ukpocopy.postcodes import UKPostcode
from ukpocopy.exceptions import PostcodeValidationError
# valid postcode
postcode = UKPostcode("SW1W 0NY") # returns UKPostcode instance
# invalid postcode
try:
postcode = UKPostcode("0000 000") # raises some PostcodeValidationError exception
except PostcodeValidationError:
# handle validation errors
pass
All validation errors inherit from PostcodeValidationError
exception. This is the list of available validation errors:
- InvalidDoubleDigitDistrictValidationError
- InvalidFinalTwoLettersError
- InvalidFirstPositionLetterValidationError
- InvalidFourthPositionLetterValidationError
- InvalidPostcodeFormatValidationError
- InvalidSecondPositionLetterValidationError
- InvalidSingleDigitDistrictValidationError
- InvalidTenDigitForDistrictAreaValidationError
- InvalidThirdPositionLetterValidationError
- InvalidZeroDigitForDistrictAreaValidationError
- InvalidCentralLondonSingleDigitDistrictValidationError
ukpocopy
uses formatted string literals to format postcodes.
UKPostcode
has the following attributes you want to use in order to render them the way you need:
postcode = UKPostcode("SW1W 0NY")
f"{postcode.outward_code}{postcode.inward_code}" # returns "SW1W0NY"
postcode = UKPostcode("SW1W 0NY")
f"{postcode.code.lower()}" # returns "sw1w 0ny"
Find more info about how to code here.
This project is licensed under the MIT License - see the LICENSE file for details.