How to copy / replace the first letter in a column if that letter is "N" and replace with "C" in the field name "DISTRICT" inside the attribute table in ArcMap using Python inside the field calculator?
closed as off-topic by Dan C, Kadir Şahbaz, csk, BERA, ahmadhanb Apr 5 at 1:08
This question appears to be off-topic. The users who voted to close gave this specific reason:
- "When seeking help to debug/write/improve code always provide the desired behavior, a specific problem/error and the shortest code (as formatted text, not pictures) needed to reproduce it in the question body. Providing a clear problem statement and a code attempt helps others to help you." – Dan C, Kadir Şahbaz, csk, BERA, ahmadhanb
The general format for overall string replace in Python in the Field Calculator is
= !stringvar!.replace("substring to find", "new substring")
If you want to only change the first initial for all records, you could build this based on a slice of the string.
= "C" + !stringvar![1:]
If you only want to change the first initial if it starts with a "N", then you're getting into conditional statements (if/then) and should wrap this in a function for use within the Field Calculator. Build this in the codebook/pre-Logic script code.
def replaceIfN(fieldtochange): if fieldtochange.lower().startswith("n"): # handles both n and N return "C" + fieldtochange[1:] else: # no change made return fieldtochange
Run this with
You can add a number to the python replace code to determine how many instances to change (in your case just one):
!District!.replace("C", "N", 1)
Using vbscript instead if you're working in ArcGIS Desktop, The code is:
- the first 1 equals the line position (first character)
- and the second 1 is amount of characters to change (only need to change one letter per row, not all C's and N's).