String formatting in Python is the process of building a string representation dynamically by inserting the value of numeric expressions in an already existing string. Python’s string concatenation operator doesn’t accept a non-string operand. Hence, Python offers following string formatting techniques −
Using % operator
The “%” (modulo) operator often referred to as the string formatting operator. It takes a format string along with a set of variables and combine them to create a string that contain values of the variables formatted in the specified way.
Example
To insert a string into a format string using the “%” operator, we use “%s” as shown in the below example −
Open Compiler
name ="Tutorialspoint"print("Welcome to %s!"% name)
It will produce the following output −
Welcome to Tutorialspoint!
Using format() method
It is a built-in method of str class. The format() method works by defining placeholders within a string using curly braces “{}”. These placeholders are then replaced by the values specified in the method’s arguments.
Example
In the below example, we are using format() method to insert values into a string dynamically.
Open Compiler
str="Welcome to {}"print(str.format("Tutorialspoint"))
On running the above code, it will produce the following output −
Welcome to Tutorialspoint
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
Using f-string
The f-strings, also known as formatted string literals, is used to embed expressions inside string literals. The “f” in f-strings stands for formatted and prefixing it with strings creates an f-string. The curly braces “{}” within the string will then act as placeholders that is filled with variables, expressions, or function calls.
Example
The following example illustrates the working of f-strings with expressions.
Open Compiler
item1_price =2500
item2_price =300
total =f'Total: {item1_price + item2_price}'print(total)
The output of the above code is as follows −
Total: 2800
Using String Template class
The String Template class belongs to the string module and provides a way to format strings by using placeholders. Here, placeholders are defined by a dollar sign ($) followed by an identifier.
Example
The following example shows how to use Template class to format strings.
Open Compiler
from string import Template
# Defining template stringstr="Hello and Welcome to $name !"# Creating Template object
templateObj = Template(str)# now provide values
new_str = templateObj.substitute(name="Tutorialspoint")print(new_str)
It will produce the following output −
Hello and Welcome to Tutorialspoint !
Leave a Reply