featureclass = r"C:\my feature class" qry = "Item_Name = 'John's Cabin' " arcpy.SearchCursor(featureclass, qry)
qry = "Item_Name" = 'John''s Cabin' and if that doesn't work: qry = """ "Item_Name" = 'John''s Cabin' """
You need to enclose the field (Item_Name) in double quotes, the string value in single quotes (John's Cabin), definately escape the apostrophe with another one (John''s Cabin), and possibly wrap the whole thing in escaped double quotes. See this page (Chicago examples), and try it yourself in the Select Layer By Attribute toolbox tool expression builder. I would try:qry = "Item_Name" = 'John''s Cabin' and if that doesn't work: qry = """ "Item_Name" = 'John''s Cabin' """
No that isn't it. The problem isn't in the ITEM NAME but rather in the value "John's Cabin"
because ArcMap is expecting single quotes to be around the value - but in this case the apostrophe messes that all up.
So far, using the double quotes in python doesn't seem to work nor does using the escape character \.
qry = """Item_Name"" = 'John''s Cabin' "
I t didn't work because there was an error in the first line suggested. It should have been:qry = """Item_Name"" = 'John''s Cabin' "
The two single quotes together are SQL specific, not Python specific and that is how you include a single quote in an SQL query. (Done it many times with an FGDB).
# fixing FN name if apostrophe exists if string.find(fn_name, "'") <> -1: print 'fixing apostrophe in', fn_name, 'to be queryable.' fn_name_qry = string.replace(fn_name, "'", "''") print fn_name_qry else: fn_name_qry = fn_name cad_qry = cad_itm + ' = \'' + fn_name_qry + '\''
Issue is that SQL query syntax needs to escape single quote, which is done by using two single quotes:
' (in John's) needs to become '' in SQL syntax
I think easiest way is to split out the search term into a variable:
qry_item_value = "John's Cabin"
qry_item_value_fixed = qry_item_value.replace("'", "''")
qry = "Item_Name = '%s'" % qry_item_value_fixed