# Field calculator: add space before last 3 characters?

2837
8
11-09-2017 08:56 AM
Occasional Contributor II

Hi,

I have a Postcode point file where all the postcodes are formatted with no space. ie: AB109XY

I've made another blank text field to contain all the postcodes but with a space instead. ie. AB10 9XY

The space will always come before the last 3 characters of the string.

Can someone provide me with a VB or python code to enter into ArcMap field calculator?

Thanks.

1 Solution

Accepted Solutions
MVP Legendary Contributor

``````postcodes = ['ABC123', 'DEF45', 'GHI']
for pc in postcodes:
print('{} {}'.format(pc[:3], pc[3:]))

ABC 123
DEF 45
GHI ‍‍‍‍‍‍‍``````

so all you need in the field calculator is

``````'{} {}'.format(!pc![:3], !pc![3:])  # --- python parser, 'pc' is the field
# ---- or
'{} {}'.format(!pc![:3], !pc![3:]).strip()  #--- to strip leading trailing spaces‍‍‍``````
8 Replies
Esri Esteemed Contributor

You could use the Python syntax and use this function:

``````def corrPC(postcode):
if len(postcode) == 7:
return postcode[:4] + " " + postcode[4:]
else:
return postcode‍‍‍‍‍‍‍‍‍‍``````

Occasional Contributor II

Thanks. That's added a space for every 7 character postcode.

However, some postcodes are only 6 characters in lenght. Guess I'll just change the 7 to 6...

Occasional Contributor II

Ah actually had to change the 7 to 6 and the last 4 to 3

thanks!

Esri Esteemed Contributor

In that case you could have done this:

``````def corrPC(postcode):
if len(postcode) in [6, 7]:
return postcode[:len(postcode)-3] + " " + postcode[len(postcode)-3:]
else:
return postcode
‍‍‍‍‍``````

Be careful not to rerun the expression, since a postcode with original length of 6 will turn 7 and get an additional space.

Occasional Contributor II

Ok it turns out there are a few 5 character postcodes.

Like: M73NE

Would I now need to make it:

``````def corrPC(postcode):
if len(postcode) in [5, 6, 7]:
return postcode[:len(postcode)-3] + " " + postcode[len(postcode)-3:]
else:
return postcode``````
Esri Esteemed Contributor

Yes (if you still need to insert the space before the last three characters)

MVP Legendary Contributor

``````postcodes = ['ABC123', 'DEF45', 'GHI']
for pc in postcodes:
print('{} {}'.format(pc[:3], pc[3:]))

ABC 123
DEF 45
GHI ‍‍‍‍‍‍‍``````

so all you need in the field calculator is

``````'{} {}'.format(!pc![:3], !pc![3:])  # --- python parser, 'pc' is the field
# ---- or
'{} {}'.format(!pc![:3], !pc![3:]).strip()  #--- to strip leading trailing spaces‍‍‍``````
MVP Esteemed Contributor

Check the following expression in Python Parser.

``(!POSTCODE! [:(len( !POSTCODE!)-3)] + " " + !POSTCODE! [(len( !POSTCODE!)-3):]‍).strip()‍``

Think Location