Select to view content in your preferred language

Field calculator: add space before last 3 characters?

3698
8
Jump to solution
11-09-2017 08:56 AM
TheodoreF
Frequent Contributor

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
DanPatterson_Retired
MVP Emeritus

Canada eh?

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

View solution in original post

8 Replies
XanderBakker
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‍‍‍‍‍

TheodoreF
Frequent Contributor

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...

0 Kudos
TheodoreF
Frequent Contributor

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

thanks!

0 Kudos
XanderBakker
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.

TheodoreF
Frequent Contributor

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
0 Kudos
XanderBakker
Esri Esteemed Contributor

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

0 Kudos
DanPatterson_Retired
MVP Emeritus

Canada eh?

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
JayantaPoddar
MVP Esteemed Contributor

Check the following expression in Python Parser.

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


Think Location