Skip to content

Instantly share code, notes, and snippets.

@do-me
Last active December 28, 2023 10:43
Show Gist options
  • Select an option

  • Save do-me/c2a6fdf29a7ee3837cf94a57920cad4b to your computer and use it in GitHub Desktop.

Select an option

Save do-me/c2a6fdf29a7ee3837cf94a57920cad4b to your computer and use it in GitHub Desktop.
Separate street & housnumber
def separate_street_and_number(address):
'''
Split by " " and check for the index of the first element that STARTSWITH a number.
Everything before that index is the street name, so " ".join()
Everything after is the house number.
# K1 | 1-4
# E1 | 15
# Bahnhofstr. | 27
# Marienbrunnen | 10 a
# Bunte Allee | 2 a-c
# Goethestr | 7a
https://gist.github.com/do-me/c2a6fdf29a7ee3837cf94a57920cad4b
'''
# Split the address by spaces
parts = address.split(" ")
# Find the index of the first element that STARTSWITH a number
index = next((i for i, part in enumerate(parts) if part and part[0].isdigit()), None)
if index is not None:
# Everything before the index is the street name
street_name = " ".join(parts[:index])
# Everything after the index is the house number
house_number = " ".join(parts[index:]) if index < len(parts) else None
return street_name, house_number
else:
# No valid house number found, return the entire address as the street name
return address, None
@do-me

do-me commented Dec 14, 2023

Copy link
Copy Markdown
Author

Logic from me, (slightly modified) code from ChatGPT with this prompt:

I need an efficient python function that separates streetname from housenumber (and additions).
These are examples

K1 1-4
E1 15
Bahnhofstr. 27
Marienbrunnen 10 a
Bunte Allee 2 a-c

Implement this logic:

  1. Split by " " and check for the index of the first element where only numbers and minues occur so that entries like "10" or "2-4" are both valid but "E7" is not.
  2. Everything before that index is the street name, so " ".join()
  3. Everything after is the housenumber

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment