Python format() Function

The format() function in Python is used to format specified values and insert them into a string’s placeholder. The placeholders are defined using curly braces {}. This function provides a flexible way to construct strings with dynamic content and control the presentation of values.

Table of Contents

  1. Introduction
  2. format() Function Syntax
  3. Understanding format()
  4. Examples
    • Basic Usage
    • Positional and Keyword Arguments
    • Formatting Numbers
    • Formatting Strings
  5. Real-World Use Case
  6. Conclusion

Introduction

The format() function allows you to create strings with dynamic content by inserting specified values into placeholders within the string. This is particularly useful for generating formatted output, such as reports, logs, and user-friendly messages.

format() Function Syntax

The syntax for the format() function is as follows:

str.format(*args, **kwargs)

Parameters:

  • args: Positional arguments to be inserted into the string.
  • kwargs: Keyword arguments to be inserted into the string.

Returns:

  • A formatted string with the specified values inserted into the placeholders.

Understanding format()

The format() function uses curly braces {} as placeholders within the string. These placeholders can be empty, positional, or keyword-based, allowing for flexible insertion and formatting of values.

Examples

Basic Usage

To demonstrate the basic usage of format(), we will insert values into a string using placeholders.

Example

name = "Ramesh"
age = 28
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)

Output:

My name is Ramesh and I am 28 years old.

Positional and Keyword Arguments

This example shows how to use positional and keyword arguments with the format() function.

Example

formatted_string = "My name is {0} and I am {1} years old. I live in {city}.".format("Sita", 30, city="Mumbai")
print(formatted_string)

Output:

My name is Sita and I am 30 years old. I live in Mumbai.

Formatting Numbers

This example demonstrates how to format numbers using the format() function, including specifying precision for floating-point numbers.

Example

pi = 3.141592653589793
formatted_string = "The value of pi to two decimal places is {:.2f}".format(pi)
print(formatted_string)

Output:

The value of pi to two decimal places is 3.14

Formatting Strings

This example shows how to format strings to a specific width and alignment.

Example

formatted_string = "Name: {:<10} | Age: {:>3}".format("Mohan", 25)
print(formatted_string)

Output:

Name: Mohan      | Age:  25

Real-World Use Case

Generating Reports

In real-world applications, the format() function can be used to generate formatted reports.

Example

report_template = """
Employee Report
---------------
Name: {name}
Department: {department}
Age: {age}
Salary: ${salary:.2f}
"""

report = report_template.format(
    name="Lakshmi",
    department="Finance",
    age=29,
    salary=55000.75
)

print(report)

Output:


Employee Report
---------------
Name: Lakshmi
Department: Finance
Age: 29
Salary: $55000.75

Logging

Another real-world use case is logging, where the format() function can be used to construct log messages with dynamic content.

Example

import datetime

log_template = "[{timestamp}] {level}: {message}"
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_message = log_template.format(timestamp=timestamp, level="INFO", message="Application started")
print(log_message)

Output:

[2024-07-22 18:19:50] INFO: Application started

Conclusion

The format() function in Python is used for creating formatted strings with dynamic content. By using this function, you can easily construct strings with specified values inserted into placeholders, making it particularly helpful for generating reports, logs, and user-friendly messages in your Python applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top