String formatting in python | String interpolation in python

String formatting or Interpolation is an essential part of any programming language. In python string formatting can be done in different ways. It helps a programmer to create dynamic strings on the basis of different inputs. Without string interpolation or formatting we have to duplicate the same string many times in different variables that may lead to confusion.

Python provides four ways to do string formatting or interpolation. Each and every method has its own pros and cons. You can choose anyone on the basis of your requirement or comfortability. These are four methods

  • String Formatting (% Operator)
  • String Formatting (str.format)
  • f-Strings (Python 3.6+)
  • Template Strings (Standard Library)

1. String Formatting (% Operator)

This is almost similar to ptintf() in C programming language. If you are aware of that then you can easily understand this. With this method, we can format the string according to the specified format. Let see the example

print("%d is %s age."%(23,'singhak'))
#output
23 is singhak age.
#----------
"%d" % 1    # This Example shows usage of zero padding and width flags.
#output
'1'

#--------
"%03d" % 1

#output
'001'

%s is used here for string and %d is used for integers. Similarly, we can use another formatting like %f, %.2f %G and many others. You can check more conversion flags Here. Here remember one thing it is one-to-one mapping means %d -> 23 and %s -> ‘singhak’. If you give anything extra it will throe error.

# Here we passed extra %s it cause error
print("%d is %s age %s."%(23,'singhak'))
#output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

# Here we passed extra value in tuple '4' which cause below error
print("%d is %s age."%(23,'singhak',4))
#output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

In this method we can use variable also to map our formatting string. See below example

name = 'world' 
program ='python'
print(‘Hello %(name)s! This is %(program)s.’%(name, program))
#output
Hello world! This is python.

We can use Json like object while mapping formatting string

# You can use json like object while mapping formatting string
print('Hello %(name1)s! This is %(program2)s.'%{'name1':'P','program2':'Q'})
#output
Hello P! This is Q

print('%(language)s has %(number)03d quote types.' % {"language": "Python", "number": 2})
#output
Python has 002 quote types.

Also read: Top 20 Python interview question

2. Str.format()

In this string formatting we use format() function on a string object and braces {}, the string object in format() function is substituted in place of braces {}. We can use the format() function to do simple positional formatting, just like % formatting.

name = "Singhak"
print("Hi {}".format(name)) # Hi Singhak
print("Hi {0}".format(name)) # Hi Singhak

In the above example we used {} and format() function to map “name” to {}. Even we can pass positional value to the {} like {0} to map format function parameters according to their position.

print("Hi {1} my name is {0}".format('Singhak', 'Aksingh')) # Hi Aksingh my name is Singhak

We can also use variable to to map our formatting string. Variable name help in more readability then number.

print("Hi {name} my name is {yourname}.".format(name='Singhak', yourname='Aksingh')) # Hi Singhak my name is Aksingh.

name="Singhak"
yourname="Aksingh"
print("Hi {name} my name is {yourname}.".format(name=name, yourname=yourname)) # Hi Singhak my name is Aksingh.

In this example we specified the variable substitutions place using the name of variable and pass the variable in format().

3. f-strings

Python 3.6 introduce a new way to do string interpolation, It is better than above two methods in term of developer-friendly. It uses 'f' prefix to indicate string interpolation. It provides access to embedded Python expressions inside string constants.

name="Singhak"
yourname="Aksingh"
print(f"Hi {name} my name is {yourname}.") # Hi Singhak my name is Aksingh.

This new string interpolation is powerful as we can embed arbitrary Python expressions we can even do inline arithmetic with it.

a = 12
b = 3
print(f'12 multiply 3 is {a * b}.') # 12 multiply 3 is 36.

4. Template Strings

Template String is another way to format the string in python. It uses Template class from string module. It has a syntax somewhat similar to .format() when done with keywords, but instead of curly braces to define the placeholder, it utilises a dollar sign ($). ${} is also valid and should be in place when a valid string comes after the placeholder.

rom string import Template
name = 'world'
program ='python'
new = Template('Hello, $name! This is $program.')
print(new.substitute(name= name,program=program))
#output
Hello, world! This is python

With keyword

from string import Template
Template('$obj is $color').substitute(obj='Car',color='red')
#output
'Car is red'

Template('${obj} is ${color}').substitute(obj='Car',color='red')
#output
'Car is red'

With dictionary

from string import Template
car = dict(obj='Car', color='red')
Template('$obj is $color').substitute(car)
'Car is red'

References:

Leave a Reply