2.2. String Formatting Methods#

String formatting is an essential aspect of handling and manipulating text in Python. It allows the insertion of variables into strings, the alignment and spacing of text, and the formatting of numbers and dates, among other features. Python provides several methods for string formatting, each with its unique features and use cases [Downey, 2015, Python Software Foundation, 2024].

2.2.1. String Formatting Placeholders#

When formatting strings in Python, you can utilize a range of placeholders to dynamically insert variables and values into strings with specific formats. These placeholders are invaluable for generating dynamic output tailored to your data types and formatting preferences.

Table 2.2 lists commonly used placeholders for string formatting in Python, along with their descriptions:

Table 2.2 Commonly Used String Formatting Placeholders in Python.#

Placeholder

Description

%s

Used for inserting strings. Automatically converts various data types to strings.

%i / %d

Used for inserting integers. Both placeholders serve the same purpose.

%f

Used for inserting floating-point numbers. Precision can be controlled using format specifiers (%.2f for two decimal places, for example).

%e / %E

Used for inserting numbers in scientific notation. %e displays the exponent in lowercase, %E in uppercase.

%g / %G

Automatically chooses between %f and %e based on number magnitude. %g uses lowercase letters for the exponent < -4 or >= precision, %G uses uppercase letters.

%x / %X

Used for inserting integers in hexadecimal format. %x displays lowercase letters (a-f), %X displays uppercase letters (A-F).

%o

Used for inserting integers in octal format.

%%

Used to insert a literal percent character %, represented as %%.

Examples of String Formatting:

# Example 1: Inserting strings and integers
name = "Alice"
age = 30
formatted_string = "Name: %s, Age: %d" % (name, age)
print(formatted_string)
# Output: "Name: Alice, Age: 30"

# Example 2: Inserting floating-point numbers with precision
pi = 3.14159
formatted_pi = "Pi: %.2f" % pi
print(formatted_pi)
# Output: "Pi: 3.14"

# Example 3: Inserting numbers in scientific notation
large_number = 1234567890
formatted_large_number = "Large Number: %e" % large_number
print(formatted_large_number)
# Output: "Large Number: 1.234568e+09"

# Example 4: Inserting hexadecimal and octal numbers
decimal_number = 255
formatted_hex = "Hex: %x, Octal: %o" % (decimal_number, decimal_number)
print(formatted_hex)
# Output: "Hex: ff, Octal: 377"

# Example 5: Inserting a literal percent character
discount = 25
formatted_discount = "Discount: %d%%" % discount
print(formatted_discount)
# Output: "Discount: 25%"
Name: Alice, Age: 30
Pi: 3.14
Large Number: 1.234568e+09
Hex: ff, Octal: 377
Discount: 25%

Explanation

  • Example 1: Demonstrates basic string and integer insertion using %s and %d.

  • Example 2: Illustrates inserting a floating-point number with a specified precision using %f.

  • Example 3: Shows inserting a large number in scientific notation using %e.

  • Example 4: Displays inserting numbers in hexadecimal and octal formats using %x and %o.

  • Example 5: Inserts a literal percent character % using %%.

2.2.2. The .format() Method#

The .format() method offers a versatile approach to string formatting.

name = "John"
age = 35
greeting = "Hello, my name is {} and I am {} years old.".format(name, age)
print(greeting)
# Output: Hello, my name is John and I am 35 years old.
  • Explanation:

    • The .format() method replaces {} placeholders with values from variables (name and age).

    • This method allows for flexible string composition by substituting values into specific positions within the string.

Table 2.3 showcases the different formatting options available with Python’s .format() method, along with descriptions, examples, and their outputs:

Table 2.3 The .format() method supports various formatting options#

Syntax

Description

Example

Output

Positional Arguments

Use curly braces {} to specify positions for substitution.

"{} {}".format('John', 'Doe')

"John Doe"

Named Arguments

Use named placeholders {name} to substitute values by name.

"Hello, {name}!".format(name='Alice')

"Hello, Alice!"

Index-based Arguments

Specify argument positions with indices inside curly braces {}.

"Today is {0}, {1}".format('Monday', 'sunny')

"Today is Monday, sunny"

Accessing Object Attributes

Use dot notation to access object attributes inside placeholders.

"Coordinates: {latitude}, {longitude}".format(latitude=37.77, longitude=-122.42)

"Coordinates: 37.77, -122.42"

Formatting Numbers

Control numeric output with format specifiers inside placeholders.

"Value: {:.2f}".format(3.14159)

"Value: 3.14"

Aligning Text

Adjust text alignment within specified width using :< or :> inside curly braces.

"{:>10}".format('right')

"     right"

Examples:

# Example 1: Positional Arguments
print("Hello, {}!".format('Alice'))  # Output: Hello, Alice!

# Example 2: Named Arguments
print("Coordinates: {latitude}, {longitude}".format(latitude=51.05, longitude=-114.06))
# Output: Coordinates: 37.77, -122.42

# Example 3: Index-based Arguments
print("{0} is {1} years old.".format('John', 35))  # Output: John is 35 years old.

# Example 4: Formatting Numbers
pi = 3.14159
print("Pi value: {:.2f}".format(pi))  # Output: Pi value: 3.14

# Example 5: Aligning Text
print("{:>10}".format('right'))  # Output: "     right"
Hello, Alice!
Coordinates: 51.05, -114.06
John is 35 years old.
Pi value: 3.14
     right

2.2.3. Formatted String Literals (f-strings) in Python#

Formatted string literals, often referred to as f-strings, provide a convenient and efficient way to embed expressions inside string literals, allowing for dynamic string formatting.

Syntax and Usage: F-strings are denoted by placing an f or F prefix before the string literal. They allow for straightforward insertion of variables and expressions within curly braces {} directly inside the string.

Table 2.4 shows the different formatting options available with Python’s F-strings, along with descriptions, examples, and their outputs:

Table 2.4 F-strings: Various Formatting Options in Python#

Syntax

Description

Example

Output

Expressions inside {}

Allows embedding expressions directly within curly braces {}.

f"Hello, {name}!"

"Hello, Alice!"

Formatting Numbers

Controls numeric output with format specifiers directly inside {}.

f"Value: {pi:.2f}"

"Value: 3.14"

Aligning Text

Adjusts text alignment within specified width using <, >, ^ inside {}.

f"{name:>10}"

"     Alice"

Example: Expressions inside {}

name = "Alice"
print(f"Hello, {name}!")  # Output: Hello, Alice!
Hello, Alice!
  • This example demonstrates how to embed expressions, specifically the variable name, directly within a string using an f-string.

  • The f"Hello, {name}!" syntax denotes an f-string. The {name} placeholder is replaced with the value stored in the name variable ("Alice" in this case) when the string is formatted.

  • When executed, print(f"Hello, {name}!") outputs "Hello, Alice!".

Example: Formatting Numbers

pi = 3.14159
print(f"Pi value: {pi:.2f}")  # Output: Pi value: 3.14
Pi value: 3.14
  • In this example, pi is a floating-point number (3.14159).

  • The f-string f"Pi value: {pi:.2f}" formats the variable pi to display it as a floating-point number with two decimal places (:.2f).

  • When printed, print(f"Pi value: {pi:.2f}") outputs "Pi value: 3.14", where 3.14 is the value of pi rounded to two decimal places.

Example: Aligning Text

print(f"{'right':>10}")  # Output: "     right"
     right
  • This example demonstrates text alignment within a specified width using an f-string.

  • f"{'right':>10}" aligns the string 'right' to the right within a width of 10 characters.

  • The > symbol inside the curly braces {} specifies right alignment. Similarly, < would specify left alignment, and ^ would specify center alignment.

  • When printed, print(f"{'right':>10}") outputs "     right", with 'right' padded with spaces to fill a width of 10 characters, aligning it to the right.

2.2.4. Template Strings#

Template strings provide a simplified approach to string formatting in Python, offering a safe and straightforward way to substitute variables into strings.

Example: Basic Usage

from string import Template

# Create a template string with placeholders
template = Template("Name: $name, Age: $age")

# Substitute values into the template
formatted_string = template.substitute(name="David", age=32)

# Print the formatted string
print(formatted_string)  # Output: "Name: David, Age: 32"
Name: David, Age: 32
  • Template Creation: Use Template("template_string") to define a template with placeholders denoted by $name, $age, etc.

  • Substitution: Call .substitute() on the template object and provide keyword arguments (name="value", age=value) to replace placeholders with actual values.

  • Output: Prints the string with placeholders replaced by the specified values.

Example: Basic Variable Substitution

from string import Template

# Define a template string with placeholders
template = Template("Hello, $name! How are you today?")

# Substitute the placeholder with a variable
name = "Alice"
formatted_string = template.substitute(name=name)

# Output the formatted string
print(formatted_string)  # Output: "Hello, Alice! How are you today?"
Hello, Alice! How are you today?

Example: Substitution with Multiple Variables

from string import Template

# Template string with placeholders
template = Template("Welcome, $name! Your balance is $$balance.")

# Substitute variables
name = "John"
balance = 1500.75
formatted_string = template.substitute(name=name, balance=f"{balance:.2f}")

# Output the formatted string
print(formatted_string)  # Output: "Welcome, John! Your balance is $1500.75."
Welcome, John! Your balance is $balance.

The code uses a template with placeholders to insert the name and formatted balance into a welcome message. The balance is formatted to two decimal places using an f-string, and the final message is printed out.

Comparisons

String Formatting Placeholders (%):

  • Legacy code: Best used when maintaining or interacting with older Python code that doesn’t support newer formatting methods.

  • Simple formatting needs: Suitable for straightforward string substitutions, especially when the format is not complex.

The .format() Method:

  • Versatility: Ideal for complex formatting where you might need to reuse the same variable multiple times or access elements by index or keywords.

  • Localization: Useful when localizing strings into different languages, as it allows reordering of the display without changing the code logic.

Formatted String Literals (f-strings):

  • Readability and conciseness: Preferred for most new Python code due to its brevity and clear syntax.

  • Performance: Chosen for better performance in terms of speed, as it’s generally faster than the other methods.

  • Inline expression: When you need to embed Python expressions inside string literals and evaluate them at runtime.

Template Strings:

  • User-generated templates: Safe to use when handling format strings provided by the users, as it avoids common security issues related to string formatting.

  • Simplicity: When the formatting is very simple and doesn’t require the bells and whistles of the other methods.