I wish to add a field in an attribute table that should work as a georeferencing key. It needs to take into consideration values from a series of fields. The last field is a housenumber and it contains from one to five digits (e.g. 2, 20, 20A, 200A, 200AB etc.) What shall I write in Field calculator to ensure that the above housenumbers becomes the following values in my new field: 002 020 020A 200A 200AB

So that the numbers are always represented with 3 digits (containing preceding zeros if necessary), and possible subsequent letters are kept?


Here is a simple approach using the built-in Python .isdigit(), .isalpha() and .zfill() methods. This approach uses the Python parser.

Pre-logic Script Code:

def changeAddress(y):
  integer = ''.join(x for x in y if x.isdigit())
  string = ''.join(x for x in y if x.isalpha())
  final = integer.zfill(3)
  return final + string


enter image description here


There are several ways to calculate this, one is using regexp with Python:



code block:

def value(f):
 import re
 if len(re.findall(r'\d', f)) ==1:
  return "00{}".format(f)
 elif len(re.findall(r'\d', f)) ==2:
  return "0{}".format(f)
  return f

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.