Error in calculate field using Python

1053
4
Jump to solution
12-14-2017 03:20 PM
DuminduJayasekera
New Contributor III

Hi,

I have the following python script to create a TEXT column called "SEC" and then I need to perform a Field calculator operation for the SEC column. I want to read the corresponding string in the "mtrs" column and and fill in SEC column. I have performed this task manually and it worked. I need to slice the "mtrs" string like this "S{}".format(int( !mtrs! [17:19]))" and fill in SEC column. 

My script below give me an error in line 14. SyntaxError. invalid syntax. 

Can somebody help me to fix this and make this work?

Thanks in advance,

# Import system modules

import arcpy
from arcpy import env
 
# Set environment settings
env.workspace = "H:/Test/Points.gdb"
 
# Set local variables
inFeatures = "plsssection_test_p1"
fieldName1 = "SEC"
length = 20

expression = ""S{}".format(int( !mtrs! [17:19]))"
 
# Execute AddField twice for two new fields
arcpy.AddField_management(inFeatures, fieldName1, "TEXT", length, "", "")
arcpy.CalculateField_management(inFeatures, "SEC",expression, "PYTHON_9.3")‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos
1 Solution

Accepted Solutions
DanPatterson_Retired
MVP Esteemed Contributor
a = ""S{}".format(int( !mtrs! [17:19]))"
  File "<ipython-input-1-6325b07dafa7>", line 1
    a = ""S{}".format(int( !mtrs! [17:19]))"
          ^
SyntaxError: invalid syntax

watch your quotes... throw a single around the whole expression

a = '"S{}".format(int( !mtrs! [17:19]))'

# --- no error

View solution in original post

4 Replies
JoshuaBixby
MVP Esteemed Contributor

What about:

# Import system modules

import arcpy
from arcpy import env
 
# Set environment settings
env.workspace = "H:/Test/Points.gdb"
 
# Set local variables
inFeatures = "plsssection_test_p1"
fieldName1 = "SEC"
length = 20

expression = "!mtrs![17:19]"
 
# Execute AddField twice for two new fields
arcpy.AddField_management(inFeatures, fieldName1, "TEXT", length, "", "")
arcpy.CalculateField_management(inFeatures, "SEC",expression, "PYTHON_9.3")
DuminduJayasekera
New Contributor III

Thanks for the reply.

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor
a = ""S{}".format(int( !mtrs! [17:19]))"
  File "<ipython-input-1-6325b07dafa7>", line 1
    a = ""S{}".format(int( !mtrs! [17:19]))"
          ^
SyntaxError: invalid syntax

watch your quotes... throw a single around the whole expression

a = '"S{}".format(int( !mtrs! [17:19]))'

# --- no error
DuminduJayasekera
New Contributor III

Thank you. It worked.

0 Kudos