March 29, 2020 /   python 3.6   f-string

Python Philosophy

Before python 3.6 there were two ways to format python strings. str.format() and the % style formatting. Before we explore f-strings let's see what we are used to to.

1. str.format()

str.format() is an old style of formatting strings. It provides various ways of formatting string including positional parameters, named parameters and ordered parameters. Here are some examples.

$ python3
Python 3.5.2 (default, Oct  8 2019, 13:06:37) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> ".format() ways to format a string"
'.format() ways to format a string'
>>> 
>>> 
>>> "Python is a great {0} language".format("programming")
'Python is a great programming language'
>>> 
>>> 
>>> "Python is a great {programming} language".format(programming="programming")
'Python is a great programming language'
>>> 
>>> 
>>> "Python is a great {} language".format("programming")
'Python is a great programming language'

2. %-style string formatting

%-style formatting of string is another popular way of formatting strings in python Let's see by an example

>>> "Python is a great %s language" % ("programming")
'Python is a great programming language'
>>> 

%-style formatting is an ordered formatting i.e. parameters are replaced as they appear in order.

Performance of Old-style string formatting

Both the methods str.format() and %-style have readability and performance issues

You can learn more about their performance here

https://stackoverflow.com/questions/40714555/python-string-formatting-is-more-efficient-than-format-function/48465349

New f-strings in Python 3.6

f-strings for formatted string literals are string constants that can have un-evaluated python expressions that will be evaluated at run time.

f-strings starts with f. Let's see an example.

>>> sitename = 'hackerseve.com'
>>> f"You are reading f-strings on {sitename}"
'You are reading f-strings on hackerseve.com'

There is much more you can write in curly braces, any valid python expression, constants, function call with valid arguments.