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 % operatorThe "%" (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.
ExampleTo insert a string into a format string using the "%" operator, we use "%s" as shown in the below example −
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.
ExampleIn the below example, we are using format() method to insert values into a string dynamically.
str = "Welcome to {}" print(str.format("Tutorialspoint"))
On running the above code, it will produce the following output −
Welcome to TutorialspointUsing 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.
ExampleThe following example illustrates the working of f-strings with expressions.
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: 2800Using 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.
ExampleThe following example shows how to use Template class to format strings.
from string import Template # Defining template string str = "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 !
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4