String Interpolation in Python

String Interpolation

String interpolation is a process of injecting value into a placeholder (a placeholder is nothing but a variable to which you can assign data/value later) in a string literal. It helps in dynamically formatting the output in a fancier way. Python supports multiple ways to format string literals.

string interpolation

Ways of string interpolation

  • %-formatting
  • str.format()
  • Template Strings 
  • F-strings
strings-Interpolation in python

%-formatting –

  • In python modulo(%) operator is overloaded in str class to perform string formatting.
  • If we have lots of variable to concat , then we can use %-formatting.

code #1:

# Python program to demonstrate 
# string interpolation 
n1 = ‘Hello’
n2 =‘PrepInsta’

# for single substitution 

print(“Welcome to % s% n2) 
n3=‘Prepsters’
# for single and multiple substitutions () mandatory 
print(% s % s welcome to %s.”%(n1, n3,n2)) 

 

Output:

Welcome to PrepInsta
Hello Prepsters welcome to PrepInsta.

Str.format()

  • It is one of the string formatting methods in Python3.
  • It is used for positional formatting, this allows re-arranging the order of placeholders within string literals without changing the order they are listed in .format( ). 

Code #2:

# Python program to demonstrate 
# string interpolation 
n1 = ‘Hello’
n2 =‘PrepInsta’

# for single substitution 
print(“Welcome to {} .format(n2)) 
n3=‘Prepsters’
# for multiple substitutions  
print({b1} {b2} welcome to {b3}.”.format(b1=n1, b2=n3,b3=n2)) 
Output:

Welcome to PrepInsta
Hello Prepsters welcome to PrepInsta.

Template Strings

  • It lets you make substitutions in a string using a mapping object.
  • Here, a valid python identifier preceded by sign ‘$’ is used as a placeholder. 

Code #3:

# Python program to demonstrate 
# string interpolation 
from string import Template 
n1 = ‘Hello’
n2 =‘PrepInsta’

# made a template which we can we use
p=Template(‘Welcome to $s2’)
print(p.substitute(s2=n2))
n3=‘Prepsters’
p1=Template(‘$s1 $s2 Welcome to $s3.’)
print(p1.substitute(s1=n1, s2=n3,s3=n2)) 
Output:

Welcome to PrepInsta
Hello Prepsters Welcome to PrepInsta.

F-strings

  • F-strings provide a way to embed expressions inside string literals, using a minimal syntax.
  • In Python source code, an f-string is a literal string, prefixed with ‘f’, which contains expressions inside braces. 

Code #4:

# Python program to demonstrate 
# string interpolation 
from string import Template 
n1 = ‘Hello’
n2 =‘PrepInsta’

# for single substitution 
print(f“Welcome to {n2})
n3=‘Prepsters’ 
print(f{n1} {n3} welcome to {n2}.”
Output:

Welcome to PrepInsta
Hello Prepsters welcome to PrepInsta.