String interpolation is the process to substitute a variable value inside a string by using placeholders. String interpolation provides dynamic usage of strings and text with different string values and variables. For example, to salute different persons a string interpolation can be used for different persons with different names. “Hello <name>” example is simple string interpolation where the <name> is substituted with different names in multiple usages.
String Interpolation with f-string
The f-string
method is added with Python3.6 and provides very easy string interpolation by just using the string variables inside { }
curly brackets. The variables should be used the same name as their definition names.
name="Ismail"
print(f"Hello {name}")
age="38"
print(f"Hello {name}. You are {age} years old.")
String Interpolation with %-formatting
Python provides the %
sign which is used for a long time in order to string interpolation. The %s
is used to express string which is provided as a parameter to the print() method. The variables are provided inside the tuple which is replaced with every %s
inside the string.
name="Ismail"
age="38"
print("Hello %s. You are %s years old."%(name,age))
String Interpolation with Str.format()
Python provides the format()
method for the String type. The string type can be a string variable or a string literal. The format() method accepts the variable names which are substituted with the {}
inside the string.
name="Ismail"
age="38"
print("Hello {}. You are {} years old".format(name,age))
String Interpolation with Template Strings
The template strings can be used for string interpolation. The string type provides the substitute()
method which can be used to substitute identifiers inside a string. Identifiers start with the $
in order to define them.
from string import Template
name="Ismail"
age="38"
t = Template("Hello $name. You are $age years old")
print(t.substitute(name=name,age=age))