Mastering String Formatting in Python

% Operator Formatting

The % operator formatting method is one of the earliest approaches to string formatting in Python. It uses the % operator with a string followed by a tuple or dictionary containing values to be inserted. The % placeholders in the string are replaced by values from the tuple or dictionary.

Basic Example

username = "Charlie"
years_exp = 7

# Using % operator for string formatting
output_msg = "Developer %s has %d years of experience." % (username, years_exp)
print(output_msg)

Output:

Developer Charlie has 7 years of experience.

In this example, %s and %d are placeholders for string and integer values respectively. The values in the parentheses are inserted in order to match the placeholders.

Placeholder Types

The traditional % operator formatting supports various placeholder types:

  • %s: String
  • %d: Signed decimal integer
  • %f: Floating point number
  • %x: Hexadecimal integer
  • %o: Octal integer
  • %c: Character

Formatting Options

You can add formatting options after the placeholder to control the output format, such as specifying decimal places for floating point numbers or setting width.

scientific_value = 2.718281828459045

# Controlling decimal places and width
formatted_value = "Euler's number is approximately %.4f" % scientific_value
print(formatted_value)

Output:

Euler's number is approximately 2.7183

Dictionary Formatting

Besides tuples, you can use dictionaries for formatting where the placeholder names match the dictionary keys.

employee = {"first_name": "Diana", "position": "Senior Developer"}

# Using dictionary for formatting
result = "Employee %(first_name)s holds a %(position)s role." % employee
print(result)

Output:

Employee Diana holds a Senior Developer role.

str.format() Method

Python 2.6 introduced the str.format() method, which provides more flexible and powerful string formatting capabilities. With this method, you use {} placeholders in the string and pass corresponding values through the format() method.

Basic Example

product = "Python Programming Guide"
price = 39.99

# Using str.format() method
product_info = "The {} costs ${:.2f}.".format(product, price)
print(product_info)

Output:

The Python Programming Guide costs $39.99.

The {} placeholders indicate where values should be inserted, with values provided through the format() method call.

Positional Arguments

You can use positional arguments in {} placeholders to explicitly specify which values to insert at each position. These indices start at 0.

product_info = "The {0} costs ${1}.".format(product, price)

Keyword Arguments

Keyword arguments can also be used to specify values, making the placeholders more descriptive.

product_info = "The {item} costs ${amount}.".format(item=product, amount=price)

Placeholder Types and Formatting Options

The str.format() method supports various placeholder types and formatting options to control output format.

interest_rate = 0.035

# Controlling decimal places and width
rate_display = "Current interest rate: {:.1%}".format(interest_rate)
print(rate_display)

Output:

Current interest rate: 3.5%

Dictionary Formatting

Similar to the % operator, str.format() supports dictionary formatting.

user_profile = {"username": "Eve", "level": "Intermediate"}

# Using dictionary for formatting
profile_msg = "User {username} is at {level} level.".format(**user_profile)
print(profile_msg)

Advanced Features

The str.format() method supports advanced features like formatting expressions and selecting formatting styles.

memory_address = 4294967295

# Formatting expressions
address_display = "Memory location: {:08X}".format(memory_address)
print(address_display)

Output:

Memory location: FFFFFFFF

f-String Formatting

Python 3.6 introduced f-strings (formatted string literals), which provide a concise and intuitive way to embed expressions inside string literals. You create an f-string by prefixing the string with 'f' or 'F', and using {} placeholders to insert expression values.

Basic Example

city = "New York"
population = 8400000

# Using f-string formatting
city_info = f"{city} has a population of {population:,}."
print(city_info)

Output:

New York has a population of 8,400,000.

F-strings directly embed variables and expressions, making the code cleaner and more readable.

Expression Evaluation

F-strings support embedding any valid Python expression within {}, enabling convenient calculations and operations.

base_value = 100
tax_rate = 0.08

# Using f-strings for calculations
tax_amount = f"Tax on ${base_value} at {tax_rate:.0%} rate is ${base_value * tax_rate:.2f}"
print(tax_amount)

Output:

Tax on $100 at 8% rate is $8.00

Formatting Options

Like str.format(), f-strings support formatting options to control output format.

accuracy = 99.87654321

# Controlling decimal places and width
accuracy_display = f"Measurement accuracy: {accuracy:.3f}%"
print(accuracy_display)

Output:

Measurement accuracy: 99.877%

Tags: python String Formatting programming f-strings str.format

Posted on Sun, 14 Jun 2026 16:42:15 +0000 by leony