Skip to content

Check if item to geocode begins with a number in Python

An answer to this question on Stack Overflow.

Question

I'm reading addresses from a csv to geocode them. Currently my Python script checks if the address contains a number with this (I only want to geocode addresses that begin with a number, e.g. "81 St Nowhere street, New York"):

if hasNumbers(item) == True:

However, this means an address of the form "81 St Nowhere street, New York" would work AND so would "The Silly Boat, Pier 6, New York".

I only want addresses that start with a number in the first position to be geocoded (i.e. ignore the Pier 6 type addresses, and only geocode addresses that start with a number).

What's the easiest way to do that?

Answer

Test if the first character is a number.

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False
for item in items:
  if is_number(item[0]):
    #Do stuff

In Python3 you can just use:

for item in items:
  if item[0].isnumeric():
    #Do stuff