Skip to main content

python-string-formatting

jsx
---
title: Python String Formatting
description: Learn different methods to format strings in Python, including %-formatting, str.format(), and f-strings, with practical examples and best practices.

---

# Python String Formatting

In Python programming, string formatting is a powerful technique that allows you to create dynamic text by embedding variables and expressions within strings. Mastering string formatting is essential for creating readable code and presenting data in a user-friendly way.

## Introduction to String Formatting

String formatting refers to the process of embedding values into predefined text strings. Rather than concatenating strings with `+` operators, formatting provides cleaner syntax and more readable code. Python offers several methods for string formatting:

1. Old-style formatting using `%` operator
2. `str.format()` method
3. f-strings (formatted string literals)
4. Template strings from the `string` module

Let's explore each method to understand their syntax, advantages, and common use cases.

## Old-style Formatting with %

The `%` operator is Python's oldest string formatting method, inspired by C's `printf()` syntax.

### Basic Syntax

```python
"String with %s placeholder" % value

For multiple values, use a tuple:

python
"String with %s and %d placeholders" % (string_value, integer_value)

Common Format Specifiers

  • %s - String (or any object with a string representation)
  • %d - Integer
  • %f - Float
  • %x - Hexadecimal
  • %.2f - Float with precision (2 decimal places)

Examples

python
name = "Alice"
age = 25
height = 1.75

# Basic formatting
print("Name: %s" % name)
# Output: Name: Alice

# Multiple values
print("%s is %d years old" % (name, age))
# Output: Alice is 25 years old

# Formatting with precision
print("Height: %.2f meters" % height)
# Output: Height: 1.75 meters

# Width specification
print("Name: %10s" % name) # Right-aligned with width 10
# Output: Name: Alice

# Zero padding for numbers
print("ID: %04d" % 42)
# Output: ID: 0042

While still supported, this method is considered outdated, and newer formatting techniques are recommended for modern Python code.

The str.format() Method

Introduced in Python 3, the str.format() method offers more flexibility and readability compared to %-formatting.

Basic Syntax

python
"String with {} placeholder".format(value)

Examples

python
name = "Bob"
age = 30

# Basic formatting
print("Hello, {}!".format(name))
# Output: Hello, Bob!

# Multiple values
print("{} is {} years old".format(name, age))
# Output: Bob is 30 years old

# Positional arguments
print("{1} is {0} years old".format(age, name))
# Output: Bob is 30 years old

# Named arguments
print("{name} is {age} years old".format(name=name, age=age))
# Output: Bob is 30 years old

# Formatting options
pi = 3.14159
print("Pi is approximately {:.2f}".format(pi))
# Output: Pi is approximately 3.14

# Alignment and padding
print("{:10}|{:<10}|{:^10}|{:>10}".format("right", "left", "center", "right"))
# Output: right |left | center | right

The str.format() method supports a rich set of formatting options:

  • {:d} - Integer
  • {:.2f} - Float with precision
  • {:10} - Minimum width
  • {:<10} - Left alignment
  • {:^10} - Center alignment
  • {:>10} - Right alignment
  • {:,} - Number with thousand separators

F-Strings (Formatted String Literals)

Introduced in Python 3.6, f-strings provide the most concise and readable way to format strings. They allow you to directly embed expressions inside string literals using curly braces.

Basic Syntax

python
f"String with {variable} and {expression}"

Examples

python
name = "Charlie"
age = 35
height = 1.82

# Basic variable insertion
print(f"Hello, {name}!")
# Output: Hello, Charlie!

# Expressions inside f-strings
print(f"{name} is {age} years old and will be {age + 1} next year.")
# Output: Charlie is 35 years old and will be 36 next year.

# Formatting options
print(f"Height: {height:.2f} meters")
# Output: Height: 1.82 meters

# Arithmetic operations
print(f"5 + 10 = {5 + 10}")
# Output: 5 + 10 = 15

# Dictionary access
person = {"name": "David", "job": "Engineer"}
print(f"{person['name']} works as an {person['job']}")
# Output: David works as an Engineer

# Multi-line f-strings
message = f"""
Name: {name}
Age: {age}
Height: {height:.2f}m
"""
print(message)
# Output:
# Name: Charlie
# Age: 35
# Height: 1.82m

F-strings support all the formatting options available in str.format() but with cleaner syntax and better performance.

Template Strings

For simple string substitution, Python's string module provides a Template class that offers a simpler, though less powerful, alternative.

python
from string import Template

name = "Eve"
t = Template("Hello, $name!")
result = t.substitute(name=name)
print(result) # Output: Hello, Eve!

# With dictionary
data = {"name": "Frank", "age": 40}
t = Template("$name is $age years old")
result = t.substitute(data)
print(result) # Output: Frank is 40 years old

Template strings are useful when working with user-provided strings to reduce security risks, as they have more limited functionality.

Real-world Applications

1. Generating Reports

python
def generate_sales_report(name, items_sold, revenue, date):
report = f"""
SALES REPORT
============
Date: {date}
Sales Representative: {name}

Performance Summary:
- Items Sold: {items_sold}
- Total Revenue: ${revenue:.2f}
- Average Price: ${revenue/items_sold:.2f}

Status: {"Excellent" if items_sold > 50 else "Good" if items_sold > 30 else "Needs Improvement"}
"""
return report

print(generate_sales_report("John Smith", 45, 5249.99, "2023-05-15"))

2. User Interface Messages

python
def get_welcome_message(username, last_login, unread_messages):
time_since_login = "today" # In a real app, calculate from last_login

message = f"Welcome back, {username}! "

if unread_messages == 0:
message += "You have no new messages."
elif unread_messages == 1:
message += "You have 1 unread message."
else:
message += f"You have {unread_messages} unread messages."

message += f"\nYour last login was {time_since_login}."

return message

print(get_welcome_message("sarah_dev", "2023-05-14", 3))

3. URL Construction

python
def build_api_url(base_url, endpoint, params):
query_string = "&".join([f"{key}={value}" for key, value in params.items()])
return f"{base_url}/{endpoint}?{query_string}"

url = build_api_url(
"https://api.example.com",
"search",
{"query": "python", "limit": 10, "sort": "relevance"}
)
print(url)
# Output: https://api.example.com/search?query=python&limit=10&sort=relevance

4. Log Formatting

python
import time

def log_event(level, message, source=None):
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
source_str = f"[{source}]" if source else ""

log_line = f"{timestamp} {level:5}: {source_str} {message}"
print(log_line)

log_event("ERROR", "Database connection failed", "db_module")
log_event("INFO", "Application started")

Best Practices for String Formatting

  1. Use f-strings for most cases: They're more readable, concise, and performant.

  2. Choose the right method for the job:

    • Use f-strings for simple formatting and when expressions are needed
    • Use str.format() when you need to reuse a format string
    • Use Template strings when dealing with user-provided format strings
  3. Avoid mixing different formatting styles in the same codebase for consistency.

  4. Format numbers appropriately: Use the formatting options to control precision and display.

    python
    amount = 1234567.89
    print(f"Amount: ${amount:,.2f}") # Output: Amount: $1,234,567.89
  5. Handle long strings by using multi-line formatting:

    python
    long_message = (
    f"Dear {customer_name},\n"
    f"Thank you for your purchase of {product_name}.\n"
    f"Your order #{order_id} will be shipped on {ship_date}."
    )

Summary

Python offers multiple ways to format strings, each with its own advantages:

  • %-formatting: Legacy approach, still used in older codebases
  • str.format(): More powerful and readable than %-formatting
  • f-strings: Most concise and readable method, with direct expression evaluation
  • Template strings: Simpler, safer alternative for specific use cases

String formatting is an essential skill that helps you create dynamic, readable text for various applications, from simple console output to complex report generation.

Exercises

  1. Convert the following string using each of the three main formatting methods:

    "Hello, my name is NAME and I am AGE years old."
  2. Create a function that formats a table of data (name, age, score) using string formatting.

  3. Write a program that asks the user for their name and birth year, then uses string formatting to display their name and age.

  4. Create an f-string that includes a conditional expression to display "Pass" or "Fail" based on a score variable.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)