In python 3.6 we have f string way to format strings. Its more readable, easy, reliable, fast and stable then previous ways of formatting.

During this post we will try to understand more about this methods and see how its better then previous methods of formatting in Python. Before go further on f string method, let’s see previous methods to format strings in Python

Previous methods of formatting in Python

In earlier python version we have two major way to format strings its wither %-formatting and str.format(). We will see in short how we can work with these formatting ways.

First we talk about %-formatting style which is introduced in earliest versions and also similar to other languages and still used in old-fashioned languages lot.Although Python documentation is also not suggest to use this, it contain following note for it

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors.
Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.

Let’s see how to use this method while working in Python.

How to use %-formatting

As mentioned it’s provided from earliest version of python, so we can use % operator like below to format string.

>>> name="ssirohi"
>>> age=36
>>> "hello My name is %s" % name
'hello My name is ssirohi'

In case we have multiple variable to call, we can also use them in tuple like below.

>>> name="ssirohi"
>>> age=36
>>> "hello My name is %s and age of %s" % (name,age)
'hello My name is ssirohi and age of 36'

When we start using it more and more with many variables it become less readable, difficult to debug and handle. But i know person are still using it because they either don’t want to adopt new ways or unaware of new methods.

How to use str.format()

This is improved way to format string in Python.Personally this is my favorite way to format string in Python, which having various options to work and also easy to maintain.This Could also integrate with many Data Type in Python which make its reliable to work in any case.

Let’s see one simple examples with one Linux Command which could explain how we can use format string

>>> old_nic="ens3"
>>> new_nic="eth0"
>>> cmd = "ip add link set {} name {}".format(old_nic,new_nic)
>>> cmd
'ip add link set ens3 name eth0'

In above command we create one Linux command with two variables which could easily able to use in many ways to run.

In Format we can use {} to get replace with variable mentioned in tuple with format keyword in index order, but we can also make one variable again and again without repeating it

# Using variable name for calling
>>> name="python"
>>> "{0} 3.7 has many new features which make it more suitable then {0} 2.7".format(name)
'python 3.7 has many new features which make it more suitable then python 2.7'

# Even can use direct string 
>>> "{0} 3.7 has many new features which make it more suitable then {0} 2.7".format("python")
'python 3.7 has many new features which make it more suitable then python 2.7'

Above Output we can see we may use one format variable multiple times in string content, we need to provide index value format variables that we need to use. We can also use them in any order like below.

>>> ip=""
>>> netmask=""
>>> cmd="ifconfig eth0 {1} netmask {0}".format(netmask,ip)
>>> cmd
'ifconfig eth0 netmask'

Above command we intentionally reverse the order of variable in format tuple and we can we it worked simple as in previous example.

Format using list and dictionary

We can also use list slices or dictionary in format in same way as they used in normal python code. Let’s see some examples how we can use list and dictionary in string format.

Below examples we tried to explain, how we can use list during python string format. We created list ip_config that contain two items that could use while assigning IP address on

>>> ip_config=["",""]
>>> cmd="ifconfig eth0 {0} netmask {1}".format(ip_config[0],ip_config[1])
>>> cmd
'ifconfig eth0 netmask'

Follwing examples we tried to explain, how we can use dictionary during python string format. We created dictionary as mentioned in above list example.

>>> ip_config={"ip":"","mask":""}
>>> cmd="ifconfig eth0 {0} netmask {1}".format(ip_config["ip"],ip_config["mask"])
>>> cmd
'ifconfig eth0 netmask'

f-String: New way to format Python String

So in many examples we see how we can use str.format and its worked well in many of python code examples. It has also flexible features with good readable as compared to %-format. If you like to know my view, its really easy to work with str.format.
But as a matter of progress with time and updated version, python introduce another way of str formatting in Python3.6, which is called as f-string.You can read detail in PEP 498 (Author Eric V.Smith).
As previous mention method are co-exist their its previous methods, no previous methods has been removed from python, we still can use any of it in Python code or no need to update old python codes with this methods to work.

So this is very easy to use, readable and flexible to use in many ways. It start with f in start and used curly braces contain value inside string values that would be evaluate at run time, so this is constant values. Some examples for it


>>> f'ifconfig eth0 {ip} netmask {netmask}'
'ifconfig eth0 netmask'
>>> cmd=f'ifconfig eth0 {ip} netmask {netmask}'
>>> cmd
'ifconfig eth0 netmask'

In above command we used to print something for user output and in second example we tried to save some string value like linux command to subprocess.Popen to run later use in python code.
We can also use capital F instead of small f alphabet. We can call various functions inside it or can do same kind of calculation like below example.

>>> f'{2 * 6}'
>>> type(f'{2 * 6}')

>>> type(2*7)

In Above example, we tried to calculate some simple math as python interpreter can do, But we can see called method return string value instead of number(int or float) return without it.

>>> name="Ayaan Sirohi"                                                                      
>>> name=name.lower()                                                                        
>>> f'User name of new Team Member : {name.split()[0][0]}{name.split()[len(name.split())-1]}'
'User name of new Team Member : asirohi'                                                     

In Above statements we used some methods within f string function , we can also user defined functions as well like below

>>> from math import pi                      
>>> def circle_area(r):                      
...     area = pi*r**2                       
...     return area                          
>>> f'Area of circle : {circle_area(12)} Cm' 
'Area of circle : 452.3893421169302 Cm'      

As in ant other python statements we need to care for Quotation marks, we need to intelligently use while having multiple quotation marks, they must start and end properly, same quotation mark should not use between string.

>>> dic={'name':'ayaan', 'age':11,}                           
>>> f'Boy name is {dic["name"]} of aged {dic["age"]}'         
'Boy name is ayaan of aged 11'                                

In case we not use quotation marks in proper use, we come down to below error while running codes.

>>> f'Boy name is {dic["name"]} of aged {dic['age']}'         
  File "", line 1                                      
    f'Boy name is {dic["name"]} of aged {dic['age']}'         

Braces Use

We could use braces with f strings like below.

>>> fr'Boy name is {dic["name"]} of aged  {dic["age"]}'         
'Boy name is ayaan of aged  11'                                 
>>> fr'Boy name is {dic["name"]} of aged  {{dic["age"]}}'       
'Boy name is ayaan of aged  {dic["age"]}'                       
>>> fr'Boy name is {dic["name"]} of aged  {{{dic["age"]}}}'     
'Boy name is ayaan of aged  {11}'                               
>>> fr'Boy name is {dic["name"]} of aged  {{{{dic["age"]}}}}'   
'Boy name is ayaan of aged  {{dic["age"]}}'                     

So if we need to use braces, single brace used to get variables from any type, when we use double brace it will print as part of string. If we need to use variable inside braces, we could use triple brace, if there is no variable inside three braces, it will print as single braces. In case we need to print double braces then we need to use four braces.

>>> f'6+3'          
>>> f'{6+3}'        
>>> f'{{6+3}}'      
>>> f'{{{6+3}}}'    
>>> f'{{{{6+3}}}}'  

So basically concept behind this is like.

Single brace  --  Create expression for evaluation.
Double braces --  will escape inside braces and hence no evaluation
Three braces  --  outside braces escape second braces, so inside braces will able evaluate expression
Four braces   --  fourth and second escape its inside braces and hence no one has any expression.

One drawback is we can’t use backslash like print new line character, but with print method we could some variations in same.

>>> f'Boy name is {dic["name"]} of aged  {dic["age"]} \n'                 
'Boy name is ayaan of aged  11 \n'                                        

>>> print(f'Boy name is {dic["name"]} of aged  {dic["age"]} \n')          
Boy name is ayaan of aged  11                                             

In above we tried to use new line which didn’t work in f string method. Once it get used through print method we can make new line with f string.

Till now we came to know about various features and facts used in python string manipulation methods, out of these f sting manipulation is latest one.For further information on same topic you can refer PEP-0502