String Interpolation With Format F Strings

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)

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)
  • 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

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

88th Monthly Technical Session

IT Infrastructure Monitoring ToolHow to Choose a Suitable IT Infrastructure Monitoring Tool?

How to evaluate and compare the basic file system features and options — Welcome to TechCommanders.c

Sending mails from EC2 : Boto3 (AWS SDK for Python ) & Amazon SES

How To Get Started With Sass Or SCSS — Part I

Auto compile-time support for Unity Animation Parameters

Updates From an Aspiring Programmer

Float Community Call (Thurs 22nd April 2021) — transcript and video

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com

More from Medium

Byte Strings Are Decoded To ASCII In IO By Default In Python

How To Write Multiline Format Strings In Python

Byte Strings Are Decoded To ASCII In IO By Default In Python

How To Write Into A Single Variable From Different Modules In Python