Select to view content in your preferred language

Problems single quotes and variables used in Where Clause

2729
2
04-11-2014 05:42 AM
MattGray
Deactivated User
I did not know where else to put this.  I have a python list of string variables from an Arc Table I made, some of which contain single quotes in the middle of them.  I am trying to have a for loop iterate through use these string values in the Where Clause of a few  arcpy tools.  The only thing is that in a where clause, since a string value has to to be in single quotes, the single quote in the middle of the string values is throwing an error and messing up the quotations that Arcmap is reading in the Where Clause.  Other than having to have an update cursor go through and remove all the quotes from the string values, is there any way to get Arcpy tools with where clauses to work with strings that have a single quotation mark in them?  I have already tried escaping it with \ and r', both of which didn't work.  Any ideas?
Tags (2)
0 Kudos
2 Replies
by Anonymous User
Not applicable
Wow, that is tricky...I figured this out by doing the query manually in ArcMap...Looks like you have to escape the single quote with a another single quote...

So here were the values I was playing with:
rows = arcpy.SearchCursor("Quadrants")
>>> qts = [r.Quotes for r in rows]
>>> del rows
>>> qts
[u"test with quotes' 2", u"test with quotes' 3", u"test with quotes' 4", u"test with quotes' 5"]


To bypass the invalid expression error I had to replace the single quotes with 2 single quotes:

for q in qts:
...     where = '''"Quotes" = '{0}' '''.format(q.replace("'","''"))
...     arcpy.SelectLayerByAttribute_management("Quadrants","NEW_SELECTION", where)


This properly selected everything...That was interesting; I've never had to do that before.
0 Kudos
MattGray
Deactivated User
Thanks for the quick reply.  So far my script is working without failing, it will be interesting to see what the results are.
0 Kudos