String format() Method in Python

Python String format() Method

The format() method in Python is used to format a string by replacing placeholders (enclosed in curly braces {}) with values provided in the format() method. It allows you to create dynamic strings by inserting variables, values, or expressions into specific locations within the string.Here's the syntax of the format() method:

string.format(arg1, arg2, ...)

Parameters:

  • arg1, arg2, ...: The values or variables that will replace the placeholders in the string. You can pass multiple arguments to replace multiple placeholders.

Placeholders in the string are represented by curly braces {}. Inside the curly braces, you can include an optional index or a named identifier to specify the order of the arguments provided in the format() method.Example:

# Example using positional arguments
name = "Alice"
age = 30
message = "Hello, my name is {} and I am {} years old.".format(name, age)

print(message)

Output:

Hello, my name is Alice and I am 30 years old.

In this example, we used the format() method to create a dynamic string containing the values of the variables name and age. The curly braces {} act as placeholders and the values of name and age are provided as arguments to replace the placeholders in the string.You can also use positional indexes or named placeholders for more complex formatting:

# Example using positional indexes
item = "book"
price = 25.99
quantity = 3
order_summary = "You ordered {2} {0}s, each priced at ${1:.2f}. Total: ${3:.2f}".format(item, price, quantity, price * quantity)

print(order_summary)

Output:

You ordered 3 books, each priced at $25.99. Total: $77.97

In this example, we used positional indexes to specify the order in which the arguments should be placed in the string. The syntax {index} allows us to control the position of the arguments within the formatted string.

The format() method is powerful and versatile, making string formatting in Python flexible and expressive.