String formatting is a powerful feature in Python that allows you to create dynamic and readable strings by embedding variables within them. This is particularly useful for creating user-friendly messages, debugging information, and reports. In this blog, we will explore various methods of string formatting in Python, covering the % operator, the str.format() method, and f-strings (formatted string literals).

The % Operator

The % operator, also known as the string interpolation operator, allows you to embed variables within a string using format specifiers. Each specifier starts with % and is followed by a character representing the data type (e.g., s for string, d for integer, f for floating-point number).

Basic Usage

name = "Alice"
age = 30
formatted_str = "Name: %s, Age: %d" % (name, age)
print(formatted_str)  # Output: Name: Alice, Age: 30

Format Specifiers

  • %s – String
  • %d – Integer
  • %f – Floating-point number
  • %x – Hexadecimal integer

Example with Floating-Point Numbers

pi = 3.14159
formatted_str = "Pi rounded to two decimal places: %.2f" % pi
print(formatted_str)  # Output: Pi rounded to two decimal places: 3.14

The str.format() Method

The str.format() method is more versatile and powerful than the % operator. It allows you to use placeholders {} within a string, which can be replaced by variables using the format() method.

Basic Usage

name = "Alice"
age = 30
formatted_str = "Name: {}, Age: {}".format(name, age)
print(formatted_str)  # Output: Name: Alice, Age: 30

Positional and Keyword Arguments

You can specify the order of variables using positional arguments or use keyword arguments for better readability.

formatted_str = "Name: {0}, Age: {1}".format(name, age)
print(formatted_str)  # Output: Name: Alice, Age: 30

formatted_str = "Name: {name}, Age: {age}".format(name="Alice", age=30)
print(formatted_str)  # Output: Name: Alice, Age: 30

Formatting Numbers

You can format numbers by placing a colon : inside the placeholders, followed by a format specifier.

pi = 3.14159
formatted_str = "Pi rounded to two decimal places: {:.2f}".format(pi)
print(formatted_str)  # Output: Pi rounded to two decimal places: 3.14

Padding and Alignment

You can control the width, alignment, and padding of the formatted output.

value = 123
formatted_str = "Value: {:>10}".format(value)  # Right-align
print(formatted_str)  # Output: Value:        123

formatted_str = "Value: {:<10}".format(value)  # Left-align
print(formatted_str)  # Output: Value: 123       

formatted_str = "Value: {:^10}".format(value)  # Center-align
print(formatted_str)  # Output: Value:    123   

F-Strings (Formatted String Literals)

Introduced in Python 3.6, f-strings provide a concise and readable way to embed expressions inside string literals using curly braces {}. Precede the string with an f or F.

Basic Usage

name = "Alice"
age = 30
formatted_str = f"Name: {name}, Age: {age}"
print(formatted_str)  # Output: Name: Alice, Age: 30

Embedding Expressions

F-strings allow you to embed any valid Python expression within the curly braces.

import math
formatted_str = f"The square root of 16 is {math.sqrt(16)}"
print(formatted_str)  # Output: The square root of 16 is 4.0

Formatting Numbers

You can use the same format specifiers within f-strings as you would with str.format().

pi = 3.14159
formatted_str = f"Pi rounded to two decimal places: {pi:.2f}"
print(formatted_str)  # Output: Pi rounded to two decimal places: 3.14

Multiline f-Strings

F-strings can also span multiple lines, making them useful for creating complex, multiline strings.

name = "Alice"
age = 30
address = "123 Main St"

formatted_str = (
    f"Name: {name}\n"
    f"Age: {age}\n"
    f"Address: {address}"
)
print(formatted_str)
# Output:
# Name: Alice
# Age: 30
# Address: 123 Main St

Practical Examples

Example: Generating a Report

name = "Alice"
sales = 12345.6789

report = f"""
Sales Report
------------
Name: {name}
Total Sales: ${sales:,.2f}
"""
print(report)
# Output:
# Sales Report
# ------------
# Name: Alice
# Total Sales: $12,345.68

Example: Table Formatting

data = [
    {"name": "Alice", "age": 30, "city": "New York"},
    {"name": "Bob", "age": 25, "city": "San Francisco"},
    {"name": "Charlie", "age": 35, "city": "Chicago"},
]

formatted_str = "{:<10} {:<5} {:<15}".format("Name", "Age", "City")
for person in data:
    formatted_str += "\n{:<10} {:<5} {:<15}".format(person["name"], person["age"], person["city"])

print(formatted_str)
# Output:
# Name       Age   City           
# Alice      30    New York       
# Bob        25    San Francisco  
# Charlie    35    Chicago        

Conclusion

String formatting in Python is a powerful tool that enhances the readability and functionality of your code. Whether you use the % operator, str.format(), or f-strings, each method offers unique advantages. By mastering these techniques, you can create dynamic and user-friendly text output that makes your programs more robust and easier to understand.

Happy coding!


Leave a Reply