Python - check if given zip code (or city) is in Czech Republic

Viewed 314

I am to do some address verifications on our company database and problem is that there is another 97 or so countries apart from Czech Republic. They are quite a minority and there is no need to verificate them. Still I need to somehow set them apart, because the API I am currently using for verification can send me only response that it wasn't found.

So I am looking for some tool to recognise Czech ZIP code, or city, etc. In python.

3 Answers

The regex that zip code in Czech Republic have is [0-9]{3} [0-9]{2}|[0-9]{5}

you can simply check with re module

import re
regex = r"[0-9]{3} [0-9]{2}|[0-9]{5}"
if re.match(zipcode, regex):
    print("match")
else:
    print("not a match")

you can also use pgeocode : https://pypi.org/project/pgeocode/

Use RegEx and construct a pattern that matches Czest Republic zip codes.

According to wikipedie Czest Republic zip codes are as follows: <3 numbers><space><2 numbers>

Adding to Tal Folkman anwser you should also add \b to ensure word boundary.

import re

zip_codes = [
    "123 4",
    "123 45",
    "123 456",
    "1234",
    "12345",
    "123456"
]

for zip_code in zip_codes:
    match = re.match(pattern=r"(\b[\d]{3}[\s][\d]{2}\b|\b[\d]{5}\b)", string=zip_code)
    if match:
        print(f"Match for {zip_code}. Match result: {match.group()}.")
    else:
        print(f"No match for {zip_code}.")

Output:

No match for 123 4.
Match for 123 45. Match result: 123 45.
No match for 123 456.
No match for 1234.
Match for 12345. Match result: 12345.
No match for 123456.

Edit Use this handy website https://regex101.com/ to help you build regex patterns.

So I found the answer myself.

I can distinguish from what state selected address is thanks to geopy library.

Input:

from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent="geoapiExercises")
location = geolocation.geocode('city-name')
print(location.address)

output (in case city-name == Brno):

Brno, okres Brno-město, Jihomoravský kraj, Jihovýchod, Česko

Also I found out, that you can insert another coutry city names in your language and it will find it anyway and that is quite handy.

output (in case city-name == Mníchov):

München, Bayern, Deutschland
Related