Select to view content in your preferred language

Python String Format using a placeholder

2049
4
Jump to solution
03-24-2020 04:33 PM
NataliaGutierrez1
Regular Contributor
import arcpy

arcpy.env.workspace = r"D:\APRX_MXDS\USA_Parcels_2019_Project\Test.gdb"

List_dissolve_fc = arcpy.ListFeatureClasses("*Dissolve")  # get a list of feature classes that end with "Dissolve"

fields = ["CO_NO", "COUNTY_NAME"]  # List of fields in test.gdb

for fc in List_dissolve_fc:  # Loop through each feature class in the list
    with arcpy.da.UpdateCursor(fc, fields) as cursor: # Loop through each feature
        for row in cursor:
            row[1] = "{[-17]}".format(fc) # Update each feature in field [1] "COUNTY_NAME" using the name of the feature class without the last 17 characters. For example: walton_2019pin_Dissolve would be walton.
            cursor.updateRow(row)

Hello,

I need to loop through feature classes and in each feature class I need to update the field "COUNTY_NAME" with the name of the feature class. The problem is, that the name of the feature class is too long and I don't need to include the last 17 characters. 

For example: "walton_2019pin_Dissolve" is the name of one feature class and I only want to use "walton" in the field names. 

As you can see in the script this is written in line 12.

This method is not working.

How could I do this?

Thank you,

Natalia

0 Kudos
1 Solution

Accepted Solutions
JoshuaBixby
MVP Esteemed Contributor

Try:

row[1] = "{}".format(fc[:-17])

View solution in original post

4 Replies
JoshuaBixby
MVP Esteemed Contributor

Try:

row[1] = "{}".format(fc[:-17])
NataliaGutierrez1
Regular Contributor

Thank you so much Joshua! It worked!

0 Kudos
JoeBorgione
MVP Emeritus

While Joshua Bixby‌`s suggestion is spot on, in fact I credit him for showing me how to use format(), I've been trying to use python f strings described here:  https://realpython.com/python-f-strings/ .  

That should just about do it....
NataliaGutierrez1
Regular Contributor

Than you Joe for sharing the link. There's very good info.

0 Kudos