1

A shapefile field has text with words separated by blanks " ", dashes "-" and underscores "_". I want to standardise the words to capitalise each word, and then replace spacese (" ") with underscores.

In can do this with one type of word separator (underscores) with

arcpy.CalculateField_management(in_table="xxx.dbf", field="temp", expression="' '.join([i.capitalize() for i in !inField!.split('_', '-')]).replace(' ','_')", expression_type="PYTHON_9.3", code_block="")

but this causes words separated by spaces or dashes to not be capitalised.

I have looked at using the re package but don't know how to call re.split, which should allow splitting on multiple separators.

0

2 Answers 2

2

The easiest is probably to chain replace:

import arcpy
fc = r'C:\data.gdb\features'
fieldnames = ['infield','newfield']

with arcpy.da.UpdateCursor(fc, fieldnames) as cursor:
    for row in cursor:
        row[1] = '_'.join(row[0].replace('-',' ').replace('_', ' ').split()).title()
        cursor.updateRow(row)
0
0

Building on the code in @BERA’s answer, and looking at the help for re (https://docs.python.org/3/library/re.html), does it by using only spaces, dashes and underscores:

import re
fc = r'my dbf file'
fieldnames = ['inField','outField']
with arcpy.da.UpdateCursor(fc, fieldnames) as cursor:
    for row in cursor:
        row[1] = '_'.join(re.split(r"[\b \- \_']+", row[0])).title()
        cursor.updateRow(row)
1
  • The regex expression includes some unnecessary and duplicative characters in the set. Either [ \-\_] or [\s\-\_] works.
    – bixb0012
    Jul 30 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.