String Formatting in Python: Basic Usage of the format() Method and Argument Specification

While f-strings have become the mainstream method for embedding variable values into strings in Python 3.6 and later, understanding the format() method remains essential. It is necessary when managing strings separately as templates or when reading older Python code.

The format() method replaces replacement fields ({}) within a string with values passed as arguments.

This article explains three patterns for specifying arguments based on how the curly braces {} are used.

目次

1. Empty Braces {} (Positional Arguments)

The simplest method is to use {} as is. The arguments passed to the format() method are embedded in order from left to right.

# Definition of template string
# Values are replaced in the order that {} appears
message_template = "Ticket Number: {}, Waiting Room: {}"

# Insert values using the format method
# 105 goes into the first {}, "Room A" goes into the second {}
formatted_text = message_template.format(105, "Room A")

print(formatted_text)

Execution Result:

Ticket Number: 105, Waiting Room: Room A

If the number of arguments is less than the number of {}, an error occurs. However, if there are extra arguments, they are simply ignored.

2. Field Numbers {0} (Index Specification)

By writing a number (index) inside the {}, it is possible to explicitly specify which argument passed to format() should be used. This allows for changing the order of arguments or using the same value multiple times.

# Date format example
# Argument order: 0=Day, 1=Month, 2=Year
date_template = "Year: {2}, Month: {1}, Day: {0}"

# Arguments are passed in the order (25, 12, 2025)
formatted_date = date_template.format(25, 12, 2025)

print(formatted_date)

# Example of using the same value multiple times
# Argument 0 is used twice
winner_template = "{0} vs {1} -> Winner: {0}"
result_text = winner_template.format("TeamRed", "TeamBlue")

print(result_text)

Execution Result:

Year: 2025, Month: 12, Day: 25
TeamRed vs TeamBlue -> Winner: TeamRed

{0} refers to the first argument, and {1} refers to the second argument.

3. Field Names {name} (Keyword Argument Specification)

In this method, a name (identifier) is written inside the {}, and values are passed to the format() method as keyword arguments (name=value). This is recommended when there are many values to embed or when the template is complex, as it maximizes code readability.

# Template displaying server configuration
# It is intuitively clear what values go where
config_template = "Host: {host}, Port: {port}, Status: {status}"

# Specify values using keyword arguments
server_info = config_template.format(
    host="192.168.1.10",
    status="Active",
    port=8080  # The order of arguments does not matter
)

print(server_info)

Execution Result:

Host: 192.168.1.10, Port: 8080, Status: Active

Summary

The format() method has three usage patterns depending on the situation:

  • {}: When simply embedding values in order from the left.
  • {0}: When reordering arguments or reusing values.
  • {key}: When clarity is needed regarding which value is inserted, improving readability.

Mastering these allows for flexible string manipulation.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次