Open In App

Python String Interpolation

Last Updated : 09 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

String Interpolation is the process of substituting values of variables into placeholders in a string. Let’s consider an example to understand it better, suppose you want to change the value of the string every time you print the string like you want to print “hello <name> welcome to geeks for geeks” where the <name> is the placeholder for the name of the user. Instead of creating a new string every time, string interpolation in Python can help you to change the placeholder with the name of the user dynamically. 

Python String Interpolation

PythonStringInterpolation-(1)

% – Formatting

% – Formatting is a feature provided by Python that can be accessed with a % operator. This is similar to the printf style function in C.

Example: Formatting string using the % operator

Python3




n1 = 'Hello'
n2 = 'GeeksforGeeks'
 
# for single substitution
print("Welcome to % s" % n2)
 
# for single and multiple substitutions()
# mandatory
print("% s ! This is % s." % (n1, n2))


Output

Welcome to GeeksforGeeks
Hello ! This is GeeksforGeeks.




Let’s say it’s just a complicated version. Still, we can use it if we have a lot of variables to get substituted in the string as we don’t always want to use(“string” + variable + “string” + variable + variable + “string”) this representation. So for this purpose, we can go with %-formatting.

Note: To know more about %-formatting, refer to String Formatting in Python using %

Str.format()

str.format() works by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string. The value we wish to put into the placeholders and concatenate with the string passed as parameters into the format function. 

Example: Formatting strings using the format() method.

Python3




n1 = 'Hello'
n2 = 'GeeksforGeeks'
 
# for single substitution
print('{}, {}'.format(n1, n2))


Output

Hello, GeeksforGeeks




We can also use the variable name inside the curly braces {}. This will allow us to use the parameters of format functions in any order we want.

Example: Format functions with variables inside curly braces.

Python3




n1 = "Hello"
n2 = "GeeksForGeeks"
 
# for single or multiple substitutions
# let's say b1 and b2 are formal parameters
# and n1 and n2 are actual parameters
print("{b1}! This is {b2}.".format(b1=n1, b2=n2))
 
# we can also change the order of the
# variables in the string without changing
# the parameters of format function
print("{b2}! This is {b1}.".format(b1=n1, b2=n2))


Output

Hello! This is GeeksForGeeks.
GeeksForGeeks! This is Hello.




Note: To know more about str.format(), refer to format() function in Python

f-strings

PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). The idea behind f-strings is to make string interpolation simpler. 

To create an f-string, prefix the string with the letter “ f ”. The string itself can be formatted in much the same way that you would with str. format(). F-strings provide a concise and convenient way to embed Python expressions inside string literals for formatting.

Example: Formatting Strings using f-strings

Python3




n1 = 'Hello'
n2 = 'GeeksforGeeks'
 
# f tells Python to restore the value of two
# string variable name and program inside braces {}
print(f"{n1}! This is {n2}")


Output

Hello! This is GeeksforGeeks
(2 * 3)-10 = -4




We can also use f-strings to calculate some arithmetic operations and it will perform the inline arithmetic. See the below example – 

Example: Inline arithmetic using f-strings

Python3




a = 2
b = 3
c = 10
 
print(f"({a} * {b})-{c} = {(2 * 3)-10}")


Output

(2 * 3)-10 = -4




Note: To know more about f-strings, refer to f-strings in Python

String Template Class

In the String module, Template Class allows us to create simplified syntax for output specification. The format uses placeholder names formed by $ with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing $$ creates a single escaped $:

Example: Formatting string using Template Class

Python3




from string import Template
 
n1 = 'Hello'
n2 = 'GeeksforGeeks'
 
# made a template which we used to
# pass two variable so n3 and n4
# formal and n1 and n2 actual
n = Template('$n3 ! This is $n4.')
 
# and pass the parameters into the template string.
print(n.substitute(n3=n1, n4=n2))


Output

Hello ! This is GeeksforGeeks.




Note: To know more about the String Template class, refer to String Template Class in Python



Previous Article
Next Article

Similar Reads

Python Scipy - ndimage.interpolation.geometric_transform() function
The given mapping function is used to find, for each point in the output, the corresponding coordinates in the input Syntax: scipy.ndimage.interpolation.geometric_transform(input, mapping, order=3) Parameters input : takes an array.mapping : accepts a tuple data structure similar to length of given output array rank.order : int parameter. which is
1 min read
How to implement linear interpolation in Python?
Linear Interpolation is the technique of determining the values of the functions of any intermediate points when the values of two adjacent points are known. Linear interpolation is basically the estimation of an unknown value that falls within two known values. Linear Interpolation is used in various disciplines like statistical, economics, price
4 min read
Python OpenCV - Bicubic Interpolation for Resizing Image
Image resizing is a crucial concept that wishes to augment or reduce the number of pixels in a picture. Applications of image resizing can occur under a wider form of scenarios: transliteration of the image, correcting for lens distortion, changing perspective, and rotating a picture. The results of resizing greatly vary looking on the kind of inte
9 min read
Interpolation in Python
Interpolation in Python refers to the process of estimating unknown values that fall between known values. This concept is commonly used in data analysis, mathematical modeling, and graphical representations. Python provides several ways to perform interpolation, including the use of libraries like NumPy, SciPy, and pandas, which offer built-in fun
2 min read
Gauss's Forward Interpolation
Interpolation refers to the process of creating new data points given within the given set of data. The below code computes the desired data point within the given range of discrete data sets using the formula given by Gauss and this method is known as Gauss's Forward Method. Gauss's Forward Method: The gaussian interpolation comes under the Centra
3 min read
Interpolation Search visualizer using PyQt5
In this article we will see how we can make a PyQt5 application which will visualize the interpolation search algorithm.The Interpolation Search is an improvement over Binary Search for instances, where the values in a sorted array are uniformly distributed. Binary Search always goes to the middle element to check. On the other hand, interpolation
6 min read
SciPy Interpolation
In this article, we will learn Interpolation using the SciPy module in Python. First, we will discuss interpolation and its types with implementation. Interpolation and Its TypesInterpolation is a technique of constructing data points between given data points. The scipy.interpolate is a module in Python SciPy consisting of classes, spline function
4 min read
OpenCV - Resize without Interpolation
In Interpolation, known data is used to estimate the values at unknown locations with the help of known values. It is used in tasks such as zooming, shrinking, rotating, and geometrically correcting digital images which happens directly in spatial domain. In this article, you will learn how to resize an image using Nearest neighbor interpolation te
3 min read
Polynomial Interpolation Using Sklearn
Newton’s polynomial interpolation is a way to fit exactly for a set of data points which we also call curve fitting. Newton's polynomial is also known as Newton's divided differences interpolation polynomial because the coefficients of the polynomial are calculated using Newton's divided differences method. Divided differences (an algorithm used fo
3 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
Practice Tags :