Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python, how can I validate a UK postcode?

I have a number of UK postcodes. However, they are not well formatted. Sometimes, they look normal postcodes such as SW5 2RT, sometimes they don't have the space in the middle, but still valid such as SW52RT. But in some cases, they are wrong due to human factor, and they look like ILovePython which is totally invalid as postcodes.

So, I am wondering how can I validate the postcodes efficiently (using Python)?

Many thanks.

=================================================================

EDIT:

Thanks for the answers at: this page. But it seems only check characters in the postcode whether they are alphabet or numbers, but don't care if the combination make sense. There could be a false postcode such as AA1 1AA that get passed through the validation.

like image 949
ChangeMyName Avatar asked Feb 23 '26 03:02

ChangeMyName


2 Answers

You can use this package for your purpose:

uk-postcode-utils 0.1.0

Here it is links for the same:

https://pypi.python.org/pypi/uk-postcode-utils

Also please have a look at:

Python, Regular Expression Postcode search

like image 175
Murali Avatar answered Feb 25 '26 16:02

Murali


The UK Office for National Statistics publishes a list of UK postcodes, both current and retired, so you could pull the relevant columns out of the latest .csv download, duplicate the current ones with the space(s) removed and then do a lookup (it might be best to use a proper database such as MySQL with an index for this).

like image 43
xnx Avatar answered Feb 25 '26 15:02

xnx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!