String Interpolation With Format F Strings

Pavol Kutaj
2 min readJan 22, 2022

The aim of this pageđź“ť is to stress that format strings (f-strings) in Python offer full expression support, not just a way to interpolate variables. For example, I have a dictionary that I am sending to Slack when we publish a new document to our knowledge base in Zendesk where get_doc_URL(doc_title) is a function that looks up a URL in the manifest table.

slack_msg = {
"text": f"just published a new doc: {doc_title} \n {get_doc_URL(doc_title)}"
}

""" RESULT """
# SUPPORT-KB APP: just published a new doc: 01.01 Why Does Knowledge Base Exist?
# https://support.foo.com/hc/en-us/articles/443311002216

1. there surely were older methods for string interpolation for example format()

  • there is a downside to the traditional string interpolation with str.format() method: verbosity
>>> value = 4 * 20
>>> 'The value is {value}.'.format(value=value)
'The value is 80.'
  • you could be terser with…
>>> value = 4 * 20
>>> 'The value is {}.'.format(value)

…but that does not read well (and Readability Counts); and thus is not that well maintainable

2. but f strings offer elegant syntax with full expression support

  • the PEP 498 aims to fix this by f-strings
  • note that you need from Python 3.6 and later (running into this repeatedly)

f-strings embed expressions inside literal strings, using a minimal syntax

  • look at the value example from above
value = 4 * 20
f'The value is {value}'
  • in addition, f strings allow using any Python expression — not just simple named references
  • it is possible to call functions and populates strings with yielded return values
  • f strings support Python full expressions such as
clients = ("com.acme", "com.foo", "org.bar", "bar.foo")
>>> print(f"PLAN: DRY RUN FOR {len(clients)} CLIENTS".center(80, "-"))
#--------------------------PLAN: DRY RUN FOR 4 CLIENTS---------------------------

3. links

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com