Python’s format()
function is a versatile tool for formatting strings, allowing developers to create customized and visually appealing output. In this article, we’ll dive deep into the syntax, usage, and various formatting options provided by the format()
function, supplemented with real-world examples.
Understanding the format() Function:
The format()
function in Python is used to format strings, providing a flexible and intuitive way to insert values into placeholder fields within a string template. It supports various formatting options for controlling the appearance of the output.
1. Basic Usage:
# Basic usage of format() function
name = "Alice"
age = 30
output = "My name is {} and I am {} years old.".format(name, age)
print(output)
Output:
My name is Alice and I am 30 years old.
In this example, the format()
function replaces the placeholder {}
in the string template with the values of name
and age
.
2. Positional and Keyword Arguments:
# Positional and keyword arguments in format() function
name = "Bob"
age = 25
output = "My name is {0} and I am {1} years old. I am a {occupation}.".format(name, age, occupation="developer")
print(output)
Output:
My name is Bob and I am 25 years old. I am a developer.
Here, we use both positional and keyword arguments to fill in the placeholders in the string template.
Advanced Formatting Options:
1. Specifying Field Width and Alignment:
# Specifying field width and alignment
name = "Charlie"
age = 35
output = "Name: {:<10} Age: {:>5}".format(name, age)
print(output)
Output:
Name: Charlie Age: 35
In this example, the field width and alignment are specified using <
and >
symbols, ensuring consistent spacing in the output.
2. Formatting Numeric Values:
# Formatting numeric values
pi = 3.14159
output = "The value of pi is {:.2f}".format(pi)
print(output)
Output:
The value of pi is 3.14
Here, the :.2f
format specifier is used to format the floating-point number pi
to two decimal places.
Formatting Currency
Let’s format a monetary amount using the format()
function to display it in a currency format:
# Formatting currency
amount = 1000
formatted_amount = "Total amount: ${:,.2f}".format(amount)
print(formatted_amount)
Total amount: $1,000.00