Python code to replace individual characters using field calculator

351
5
Jump to solution
12-29-2021 12:08 PM
New Contributor III

I need to replace the 3rd and 4th digits of street addresses with 'X' and strip any apt info from the end.

Fer example "1756 Cedar St 4D' should become 17XX Cedar St

The closest I've come is:

``!USER_Address_Line_1!.replace('0123456789','X')[2:3]``
``!USER_Address_Line_1![2:3].replace('0123456789','X')``

but those just seems to turn the entire address into a single digit number

To remove the apartments, I got as far as removing numbers at the end using

``!USER_Address_Line_1!.rstrip('0123456789')``

but that still leaves lettered apartment units

I'm using ArcGIS Pro 2.8 and Python 3

1 Solution

Accepted Solutions
MVP Esteemed Contributor

Thy the following expression

Expression Type: Python 3

``(!USER_Address_Line_1![0:-2])[:2]+'XX'+(!USER_Address_Line_1![0:-2])[4:]``

or

``((!Micromarket![0:-2])[:2]+'XX'+(!Micromarket![0:-2])[4:]).strip()``

Think Location
5 Replies
MVP Esteemed Contributor

Thy the following expression

Expression Type: Python 3

``(!USER_Address_Line_1![0:-2])[:2]+'XX'+(!USER_Address_Line_1![0:-2])[4:]``

or

``((!Micromarket![0:-2])[:2]+'XX'+(!Micromarket![0:-2])[4:]).strip()``

Think Location
New Contributor III

Thank you! In terms of what I need for this data set, this absolutely works. I'm curious how you would handle it if you needed to keep the street types (RD, AVE, BLVD, CT, TER, etc.) and not all addresses had apartments. Can you run an if/then loop in field calculator?

MVP Esteemed Contributor

or generically... you can add the length check if you want

``````fld = '1756 Cedar St 4D'  # !fld!  or !YourFieldName! for the expression
def r(fld, subval="X"):
""" """
new = []
vals = fld.split(" ")
for v in vals:
for i in v:
s = "".join([subval if i in "0123456789" else i for i in v])
new.append(s)
new = " ".join(new)
return new

# -- test
r(fld)
'XXXX Cedar St XD'``````

... sort of retired...
New Contributor III

Thank you! This is a little over my head, but I feel like this is something I need to understand. By "generically" do you mean outside the field calculator environment, using a Python interpreter? And is that how I would run this script on a csv file?

MVP Esteemed Contributor

By "generically" it just doesn't replace 2 characters that are numbers but will replace any number whether it is a street address or an apartment number... even if there is no apartment.  The only issue is if you had a

"1st Avenue"

it would become "Xst Avenue"

This is a code block example

Calculate Field Python examples—ArcGIS Pro | Documentation

They are handy when a one-liner is too constrictive

... sort of retired...