Python F Strings

Since Python3.6 a new way for format strings was introduced, more readable, concise, and less prone to erros, and yes! FASTER.

The f-string aka Literal String Interpolation was introduced in the PEP 498 by Eric V. Smith, for provide a way to embed expressions inside string literals, using a minimal syntax.

Python Format

As you may know, Python supports multiple ways to format text strings:

  • %-formatting
  • str.format()
  • string.Template

Mr. Smith explains in the PEP 498 - "The existing ways of formatting are either error prone, inflexible, or cumbersome". - and yes, f-strings are the most simple/practical way (in Python3.6) for format strings.

The f-string

First, they are called f-strings because you need to prefix a string with the letter “f”; oh yeah, you remember the "u" for Unicode in Python2 or the "b" for byte string, so yes, in the same way. Now, let's take a simple dive into how the f-string works:

>>> name = "Oscar"
>>> age = 23
>>> f"Hello, {name}. You are {age}."
'Hello, Oscar. You are 23.'

Yeah, this looks like the .format() method, but this is much simpler than the old way, for example:

>>> name = "Oscar"
>>> age = 23
>>> "Hello, {name}. You are {age}.".format(name=name, age=age)
>>> # Or use positional index
>>> "Hello, {0}. You are {1}.".format(name, age)
>>> # Or omit the names inside the curly braces (Python 3.1)
>>> "Hello, {}. You are {}.".format(name, age)

Not fully convinced? f-strings also support any Python expressions inside the curly braces and you can also write triple-quoted f-strings that span multiple lines:

>>> name = "Oscar"
>>> age = 23
>>> f"Hello {name.upper()}.You are {age * 2}."
'Hello, OSCAR. You are 46.'

Did you feel that? Yeah, it's the feeling of having seen this before; as part of the ECMAScript 2015 standard, they introduced a very similar feature called “template strings” or “template literals” in the JavaScript language.

It’s good to see the JavaScript and Python communities taking inspiration from each other. In comparison with Python, in JavaScript they use the "Grave accent" instead of single or double quote and a dollar sign in front of the curly braces.

  • 1) An f-string is really an expression evaluated at run time using the format protocol, not a constant value.
  • 2) ES2015 (formally ES6) is a fantastic step forward for the JavaScript language. It brings new features and sugaring for patterns that required significant boilerplate in ES5. This includes classes, arrow functions and modules.