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.
Solved! Go to Solution.
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
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
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...
Ah actually had to change the 7 to 6 and the last 4 to 3
thanks!
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.
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
Yes (if you still need to insert the space before the last three characters)
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
Check the following expression in Python Parser.
(!POSTCODE! [:(len( !POSTCODE!)-3)] + " " + !POSTCODE! [(len( !POSTCODE!)-3):]).strip()