String formatting in Python

Strings are simple! We can just enclose whatever we want into quotes and it becomes a string. But things get complex when we want to create complex strings that may contain many escape characters and variables. In such cases, Python's String formatting functions come to our help.

Let us consider an example of a string concatenated with variables

name = 'Aaron'
city = 'Chennai'
s = 'Hey ' + name + ', ' + city + ' Welcomes you'
print(s)
 Output: Hey Aaron, Chennai Welcomes you

Here in Line 3, we have joined various bits of strings and variables using the '+' operator to get the desired output. But this method is so complex and can lead to mistakes.

Instead of hardwiring each part of the string, we can use string formatting methods to format our strings effectively the way we want.

1. The str.format() method:

This method of formatting strings is more simple than the previous method. In this method, we define the placeholders of variables within the string itself in the form of open and closed curly braces '{}'.

name = 'Aaron'
city = 'Chennai'
s = 'Hey {}, {} Welcomes you'.format(name,city)
print(s)
 Output: Hey Aaron, Chennai Welcomes you

As you can see it, this method is very simple than the method in the first example. 
Structure of str.format()

Here the first element of the tuple will be placed in the first placeholder, the second element in the second placeholder, and so on.

By default, format() function places values in placeholders in the order of the tuple which is given in the argument. But we can also place numbers within placeholders which represent the order in which the values are inserted into placeholders.

n0 = 'Aaron'
n1 = 'Kumar'
n2 = 'Vicky'
s = 'This is {2}, This is {0}, This is {1}'.format(n0,n1,n2)
print(s)
 Output: This is Vicky, This is Aaron, This is Kumar


2. The f-strings method:


The latest and probably the easiest method to format strings is the f-string method. This is the method that is recommended by Python. This method is easier, less complex, and most importantly much faster than other string formatting methods.

 Implementation of f-string:

f-strings are implemented by just adding the character 'f' in front of the string to be formatted. The values can be directly inserted into placeholders instead of defining the placeholders and giving the values as an argument in a separate function.

Here is an example,

n0 = 'Aaron'
n1 = 'Kumar'
n2 = 'Vicky'
s = f'This is {n0}, This is {n1}, This is {n2}'
print(s)
 Output: This is Aaron, This is Kumar, This is Vicky

 Let us look at the structure of f-strings in detail.
Structure of f-strings




Comments

Popular posts from this blog

Time Complexity of Basic functions in Python

Setting up/Installing Python