use the field calculator to create a python code snippet to remove the last two characters from the values in field1

728
6
12-11-2017 10:45 AM
CourtneyWade
New Contributor II

I am working on an assignment for my programming class (a class that I’m greatly struggling in) where I need to use the field calculator to create a python code snippet to remove the last two characters from the values in field 1. I know there are similar questions on this forum, yet I’m finding it hard to apply those suggestions to my problem.  Any guidance would be very much appreciated.

Thank you in advance.

0 Kudos
6 Replies
DanPatterson_Retired
MVP Emeritus

In python, strings are iterables... in the field calculator use the python parser and it would be 

!YourFieldNameHere![:-2]

of course you have to calculate this value into a new field

a = 'asdfasdfasxx'

a[:-2]

'asdfasdfas'‍‍‍‍‍

Now you didn't specify whether it is possible that the field would contain less than 2 characters.  This is a simple field calculation, so normally you would use a field calculation

and call it with

cal(!YourFieldNameHere!)

def cal(a):
    """ replace the last two characters in a field"""
    if len(a) > 2:
        return a[:-2]
    else:
        return 'Read the docs'
CourtneyWade
New Contributor II

Yes, Dan! I got it!!! Thank you! I guess I didn't realize I needed to make a new field (makes perfect sense now). I was trying to 'correct' the existing field without any luck. You helped me one other time too....I appreciate you taking the time to answer my question. 

I hope you have a great rest of your day!

Courtney

0 Kudos
DanPatterson_Retired
MVP Emeritus

no problem

0 Kudos
MicahBabinski
Occasional Contributor III

Hi Courtney,

Dan's got you covered for using the codeblock parameter within Calculate Field. It's not clear to me if your assignment requires you to use that parameter. If not, you could just run:

arcpy.CalculateField_management("Converted_Graphics", "field1", "!field1![:-2]", "PYTHON_9.3")

Keep at it. The GIS programming stuff gets easier with time, trial/error, and repetition.

Micah

CourtneyWade
New Contributor II

Hi Micah! Thank you for your suggestion. I was able to try your method on the next question and was able to make it work too.  It's is nice to know a few different ways to 'skin a cat'. My class is completely online so I'm kinda on my own here. I really appreciate you taking the time to answer my question.

Have a great day!

Courtney

0 Kudos
JoeBorgione
MVP Emeritus

A little late in the conversation, but this website is well worth the bookmark:

Python Reference (The Right Way) - DRAFT — Python Reference (The Right Way) 0.1 documentation 

That should just about do it....
0 Kudos