f-string in Python 3.6 for formatting strings

String formatting with f-strings in Python

If you are new to Python 3, learning to use f-string, Python’s relatively new string formatting is a lot of fun. f-string, a short name for “formatted string literal”, is a string literal that is prefixed with letter ‘f’ or ‘F’ and is available from Python version 3.6

There are multiple options to format a string in Python. One of them is str.format() method. For example, we can construct a string by keeping a placeholder within curly braces for the variable in a string followed by .format() method containing the variable.

>version =3.6
>'str.format(), String formatting before, Python {}.'.format(version)

would result in

'str.format(), String formatting before, Python 3.6.'

formatting strings with f-string looks a lot similar to str.format() pattern, but a lot simpler. ‘f’ character at the beginning of the string literal is similar to how Python uses ‘b’ to represent byte string or ‘r’ prefix for raw string.

The ease of f-string is you start the string that you want to format with f and followed by the string. Any variable you want to use can be specified by the variable name within curly braces inside the string. Here is a simple example using f-string with a variable.

>version = 3.6
>f'f-string is available in Python {version} or above.'
'f-string is available in Python 3.6 or above.'

If you want to format a string such that a variable should have single quotes, you can use f-string as follows

version = "3.6"
f"f-string is available in Python {repr(version)} or above."

and the output will be

"f-string is available in Python '3.6' or above."

The beauty of f-string is that it is rather versatile. It can work expression and functions. For example, let us use f-string and inside a string let us call a function and use the result to format a string.

>import math
>a = 10
># define a function
>def my_sqrt(n):
    return math.sqrt(n)
># use the function in f-string 
>f'Square root of {a} is {my_sqrt(a)}.'
'Square root of 10 is 3.1622776601683795.'