I'm using the following to write a value to a field.

arcpy.CalculateField_management (newPha, "PHACODE", """'{}'""".format(name), "PYTHON_9.3")

The only problem is that the string I'm attempting to write to the table has an apostrophe. (ex. "Saint Anne's Bay").

The single quote is clearly throwing off the expression, but the triple-double quote solution isn't working. Any ideas on how to deal with this???

  • This may be a duplicate of gis.stackexchange.com/q/238338/115 – PolyGeo May 19 '17 at 2:15
  • 1
    You need to escape the apostrophe (\') in python like "Saint Anne\'s Bay" – ahmadhanb May 19 '17 at 2:28
  • @PolyGeo I thought so too at first (and marked it as duplicate) but a re-read suggests that the single quote/apostrophe does indeed need to be escaped – Midavalo May 19 '17 at 3:17
  • 1
    @Midavalo actually it does. – ahmadhanb May 19 '17 at 3:18
  • 1
    @ahmadhanb yes I realised my mistake right after I commented. Often it doesn't matter, but in this case it does – Midavalo May 19 '17 at 3:19

Any single quotes (') can be substituted with an escaped single quote (\'). However, since the formatted string is subsequently being passed to another function for further evaluation, the escape/backslash character also needs to be escaped (\\') in the initial string.

So try it as:

arcpy.CalculateField_management (newPha, "PHACODE", """'{}'""".format(name.replace("'", "\\'")), "PYTHON_9.3")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.