Confluence Retirement

Due to the feedback from stakeholders and our commitment to not adversely impact USGS science activities that Confluence supports, we are extending the migration deadline to January 2023.

In an effort to consolidate USGS hosted Wikis, myUSGS’ Confluence service is targeted for retirement. The official USGS Wiki and collaboration space is now SharePoint. Please migrate existing spaces and content to the SharePoint platform and remove it from Confluence at your earliest convenience. If you need any additional information or have any concerns about this change, please contact Thank you for your prompt attention to this matter.
Skip to end of metadata
Go to start of metadata

Python's built-in ("batteries included") string formatting capability is especially useful in ArcGIS Python (arcpy) scripting, where you often have to build complex SQL or calculate expressions.  

For example, this SQL expression could easily be mangled:


>>> field = "ID"
>>> '"' + field + '"' + " = 0 OR " + '"' + field + '"' + ' IS NULL'
'"ID" = 0 OR "ID" IS NULL'

 (Note that in Python, double quotes in single quotes [and vice versa] are recognized as literals.)


using .format() is much easier to write, read, and debug:


>>> '"{0}" = 0 OR "{0}" IS NULL'.format(field)
'"ID" = 0 OR "ID" IS NULL'


The Calculate Field tool requires embedded quotes for its Python sub-process to recognize literal strings.

The complexity is much easier to handle using .format().


>>> site_id = "012345678"
>>> '"b{}"'.format(site_id)
>>> bstring = '"b{}"'.format(site_id)
>>> arcpy.CalculateField_management(tbl, "STAID", bstring, "PYTHON")
>>> # equivalent expression using arcpy.da.UpdateCursor:
... # note - no embedded quotes needed (not passing to subprocess)
>>> bstring = "b{}".format(site_id)
>>> bstring
>>> with arcpy.da.UpdateCursor(tbl, "STAID") as rows:
...     for row in rows:
...          row[0] = bstring
...          rows.updateRow(row)


Some formatting would be very painful without using Python's formatting functionality:

>>> "{:,.2f} KB".format(32457890 / 1024.)
'31,697.16 KB'


More information

Useful examples, and references: Python String Format Cookbook


  • No labels