Python 3: An Intro to f-strings

Python 3.6 added another way to do string interpolation that is called “f-strings” or Formatted string literals (PEP 498). The idea behind f-strings is to make string interpolation simpler. To create an f-string, you just need to prefix the string with the letter “f”. The string itself can be formatted in much the same way that you would with str.format(). In other words, you can have replacement fields in the string that are enclosed with curly braces. Here’s a simple example:

>>> name = 'Mike'
>>> f"Hello {name}"
'Hello Mike'

The Python documentation had a fun example that demonstrates how you can nest the replacement fields. I have modified it a bit to make it simpler though:

>>> total = 45.758
>>> width = 14
>>> precision = 4
>>> f"Your total is {total:{width}.{precision}}"
'Your total is          45.76'

Here we create three variables with the first one being a float and the other two being integers. Then we create our f-string and tell it that we want to put the total variable into our string. But you will note that within the string’s replacement field, we have nested the width and precision variables to format the total itself. In this case, we tell Python that we want the width of the total field to be 14 characters and the precision of the float to be 4, so the result is 45.76, which you will note is rounded up.

The f-string also supports date formatting:

>>> import datetime
>>> today = datetime.datetime.today()
>>> f"{today:%B %d, %Y}"
'March 13, 2018'

I personally like the example given in PEP 498 that actually shows how you can use the date formatting to extract the day of the week from the date:

>>> from datetime import datetime
>>> date = datetime(1992, 7, 4)
>>> f'{date} was on a {date:%A}'
'1992-07-04 00:00:00 was on a Saturday'

You can also use the same variable repeatedly in your f-string:

>>> spam = 'SPAM'
>>> f"Lovely {spam}! Wonderful {spam}!"
'Lovely SPAM! Wonderful SPAM!'

The documentation does note that you have to be careful with f-strings when nesting quotes. For example, you obviously can’t do something like this:

>>> value = 123
>>> f"Your value is "{value}""

This is a syntax error, just like it is when using a regular string. You also cannot use a backslash in your format string directly:

>>> f"newline: {ord('\n')}"
Traceback (most recent call last):
  Python Shell, prompt 29, line 1
Syntax Error: f-string expression part cannot include a backslash: , line 1, pos 0

The documentation points out that you can put the backslash into a variable as a workaround though:

>>> newline = ord('\n')
>>> f"newline: {newline}"
'newline: 10'

In this example, we convert the newline character to its ordinal value. The last item that the documentation mentions is that you can’t use an f-string as a docstring. According to Nick Coghlan, this is because docstrings need to be known at compile time, but an f-string is not resolved until runtime.

Wrapping Up

At this point you should have enough information to start using f-strings in your own code. This is a fun addition to the Python language and while not strictly necessary, I can see it making string interpolation simpler in some aspects. Have fun and happy coding!

Further Reading

https://docs.python.org/3/reference/lexical_analysis.html#f-strings

1 thought on “Python 3: An Intro to f-strings”

  1. Pingback: Python格式化字符串f-string概览(小结)-新生代

Comments are closed.