Replace character from attributes

1554
14
Jump to solution
04-27-2017 03:02 PM
CCWeedcontrol
Occasional Contributor III

I need to remove forward slashes from the attributes in a layer. I need to remove the first \ and last \ and replace the double \\ with just one \. I would appreciate any help. Thanks.

Currently the attributes looks like this.

\R2\\M1\

\M1\\M1\\C2\

\AG\\R2\\M1\\R2\

I need it to look like the following

R2\M1

M1\M1\C2

AG\R2\M1\R2

I tried the following but got error "TypeError: argument of type 'NoneType' is not iterable" on line if '\\' if '\\' in row[0]: #if a double quote is in the string returned.

with arcpy.da.UpdateCursor("In_memory\LayerTest", "ZONING_CODE") as cursor:
    for row in cursor:
         if '\\' in row[0]: #if a double quote is in the string returned,  
            row[0]=row[0].replace('\\','\\') #replace that double quote with an empty string (removes it)  
            cursor.updateRow(row)
    del row
0 Kudos
14 Replies
DanPatterson_Retired
MVP Emeritus

could you show a screen grab of the original table field... it is hard to replicate what you are talking about since a backslash is an escape character in python and what you report as inputs is hard to match for testing without having to add extra \'s which you suggest aren't there.  This may be part of the issue

0 Kudos
CCWeedcontrol
Occasional Contributor III

sure here you go.

As for why there are \ in the attribute fields is because some parcel can have more than one zoning zone and is why you would see AG\C1\M1. I couldn't use a dash ( - ) because some of our zones are CR-RR (CONDITIONAL REZONE - RURAL RESIDENTIAL) and RR(RURAL RESIDENTIAL) which are different. so if these two zoning zones were part of a parcel it would have shown as CR-RR-RR and would have been confusing.

0 Kudos
DanPatterson_Retired
MVP Emeritus

Then try Joshua's suggestion ... a.strip("\\").replace("\\\\","\\") ... but you may as well go whole tilt and fix it up altogether

a.strip("\\").replace("\\\\","/")
'AG/R2/M1/R2'

JoshuaBixby
MVP Esteemed Contributor

Does the following do what you want:

with arcpy.da.UpdateCursor("In_memory\LayerTest", "ZONING_CODE") as cursor:
    for code, in cursor:
        if code:
            cursor.updateRow([code.strip("\\").replace("\\\\","\\")])
CCWeedcontrol
Occasional Contributor III

Thanks Dan and Joshua.

0 Kudos