# Problem using field calculator to add numbers in new field with preceding zeros

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


changeAddress(!YourField!)


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

expression:

value(!f!)


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)
else:
return f