f-string in python 3.6

f-string literal

Vikash Kumar

2 minute read

f-string in python 3.6

According to python official document, f-string is a string literal that is prefixed with ‘f’ or ‘F’. This was introduced in python 3.6. Apart from usual python string formatting '%s %d' % ('python', 3.6) and the format() method, python 3.6 introduces f-string. Official doc can be found here.

f-string usage

Basic usage,

In [1]: f"%s %.1f" % ("python", 3.6)
Out[1]: 'python 3.6'

In [2]: F"%s %.1f" % ("python", 3.6)
Out[2]: 'python 3.6'

format() function style formatting:

name = 'python'
version = 3.6

In [3]: f"Software is {name} and version is {version}"
Out[3]: 'Software is python and version is 3.6'

However, you cannot use empty paranthesis as used in format(). It will result in empty expression not allowed error.

In [3]: f"Software is {} and version is {}" % (name, version)

SyntaxError: f-string: empty expression not allowed

Expression in f-string literal are treated like regular python expression surrounded by ‘{}’. If a conversion is specified, the result of evaluating the expression is converted before formatting. Conversion '!s' calls str(), '!r' calls repr() and '!a' calls ascii(). The result is then formatted using format() method.

Example from python official doc:

In [4]: f"Her name is {name !r}"
Out[4]: "Her name is 'Alice'"

Limitations

  • Backslashes `\’ are not allowed in format expression.
  • f-string can’t be used for doc string.

References

  1. https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings
  2. https://cito.github.io/blog/f-strings/
comments powered by Disqus