Table of Contents
ToggleString formatting in Python is the process of building a string representation dynamically by inserting the value of numeric expressions or variables into an existing string. Python provides several techniques for string formatting, including the % operator, the format() method, f-strings, and the String Template class. This guide explores each of these methods in detail.
The % (modulo) operator, often referred to as the string formatting operator, is one of the oldest methods for string formatting in Python. It uses format specifiers like %s for strings, %d for integers, and %f for floating-point numbers.
name = "Vista Academy"
print("Welcome to %s!" % name)
Output:
Welcome to Vista Academy!
The format() method is a built-in method of the str class. It uses curly braces {} as placeholders, which are replaced by the values provided in the method’s arguments.
str = "Welcome to {}"
print(str.format("Vista Academy"))
Output:
Welcome to Vista Academy
f-strings, or formatted string literals, are a modern and efficient way to format strings in Python. They allow you to embed expressions directly inside string literals by prefixing the string with f and using curly braces {} as placeholders.
item1_price = 2500
item2_price = 300
total = f'Total: {item1_price + item2_price}'
print(total)
Output:
Total: 2800
The String Template class, part of the string module, provides a simple way to format strings using placeholders defined by a dollar sign $ followed by an identifier.
from string import Template
# Defining template string
str = "Hello and Welcome to $name !"
# Creating Template object
templateObj = Template(str)
# Providing values
new_str = templateObj.substitute(name="Vista Academy")
print(new_str)
Output:
Hello and Welcome to Vista Academy !
Enroll in our Python certification course at Vista Academy and become a certified expert to boost your career.
Enroll Now