Home » Python String Formatting : A Tutorial with Examples

Python String Formatting : A Tutorial with Examples

String formatting in Python is an essential skill that allows you to dynamically insert variables and expressions into strings.

Python provides several ways to format strings, making it easy to display text and variables together in a readable format.

In this tutorial, we will cover:

  1. What is String Formatting?
  2. Types of String Formatting in Python
  3. Using the % Operator for String Formatting (Old Style)
  4. Using str.format() Method (New Style)
  5. Using f-strings (Python 3.6+)
  6. Formatting Numbers and Strings
  7. Escaping Curly Braces in f-strings and str.format()
  8. Advanced String Formatting

Let’s explore each method of string formatting with examples and explanations.

1. What is String Formatting?

String formatting allows you to create strings by inserting variables and expressions into placeholders within the string.

This helps make the output dynamic and readable, especially when dealing with user inputs, calculations, or displaying formatted data.

2. Types of String Formatting in Python

There are three main ways to format strings in Python:

  1. % Operator (Old Style): Common in Python 2 but still supported in Python 3.
  2. str.format() Method (New Style): More versatile and introduced in Python 3.
  3. f-strings (Literal String Interpolation): Introduced in Python 3.6, the most efficient and readable method.

3. Using the % Operator for String Formatting (Old Style)

The % operator allows you to format strings by replacing placeholders with values. It is an older method but still supported in Python.

Syntax:

"string with %s placeholder" % (value)

Common Placeholders:

  • %s: String or any object.
  • %d: Integer.
  • %f: Floating-point number.
  • %x / %X: Hexadecimal representation of an integer.

Example 1: Basic String Formatting with %

name = "Alice"
age = 30

formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)

Output:

My name is Alice and I am 30 years old.

Example 2: Formatting a Floating-Point Number with %

pi = 3.14159
formatted_string = "The value of pi is approximately %.2f." % pi
print(formatted_string)

Output:

The value of pi is approximately 3.14.
  • In this example, %.2f formats the floating-point number to 2 decimal places.

4. Using str.format() Method (New Style)

The str.format() method is more powerful and flexible than the % operator. It allows you to use placeholders within curly braces {} and pass values using the format() method.

Syntax:

"string with {} placeholders".format(value1, value2)

Example 1: Basic String Formatting with str.format()

name = "Bob"
age = 25

formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)

Output:

My name is Bob and I am 25 years old.

Example 2: Using Positional and Keyword Arguments in str.format()

formatted_string = "I have {0} apples and {1} oranges.".format(5, 10)
print(formatted_string)

formatted_string = "My name is {name} and I am {age} years old.".format(name="Charlie", age=40)
print(formatted_string)

Output:

I have 5 apples and 10 oranges.
My name is Charlie and I am 40 years old.
  • In this example, you can use positional arguments (using {0}, {1}) or keyword arguments (using {name}, {age}) to control the order and naming of the values.

5. Using f-strings (Python 3.6+)

f-strings (also known as formatted string literals) are the most modern and readable way to format strings in Python. They were introduced in Python 3.6 and allow you to embed expressions directly inside string literals prefixed with f or F.

Syntax:

f"string with {expression} placeholders"

Example 1: Basic String Formatting with f-strings

name = "David"
age = 28

formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)

Output:

My name is David and I am 28 years old.

Example 2: Expressions Inside f-strings

a = 5
b = 10

formatted_string = f"The sum of {a} and {b} is {a + b}."
print(formatted_string)

Output:

The sum of 5 and 10 is 15.
  • In this example, you can perform expressions directly inside the curly braces of an f-string.

6. Formatting Numbers and Strings

Python allows you to format numbers and strings with padding, alignment, and precision using both str.format() and f-strings.

Example 1: Formatting Floats with Precision

pi = 3.14159265359

# Using str.format()
formatted_string = "Pi to 3 decimal places: {:.3f}".format(pi)
print(formatted_string)

# Using f-string
formatted_string = f"Pi to 3 decimal places: {pi:.3f}"
print(formatted_string)

Output:

Pi to 3 decimal places: 3.142
Pi to 3 decimal places: 3.142
  • In this example, {:.3f} limits the floating-point number to 3 decimal places.

Example 2: Padding and Alignment

# Using str.format()
formatted_string = "{:<10} | {:^10} | {:>10}".format("left", "center", "right")
print(formatted_string)

# Using f-string
formatted_string = f"{'left':<10} | {'center':^10} | {'right':>10}"
print(formatted_string)

Output:

left       |   center   |      right
left       |   center   |      right
  • In this example, :<10, :^10, and :>10 specify left, center, and right alignment with a width of 10 characters.

7. Escaping Curly Braces in f-strings and str.format()

Since curly braces {} are used as placeholders in both f-strings and str.format(), you need to escape them by doubling the braces {{ and }} if you want to display them in the string.

Example: Escaping Curly Braces

# Using str.format()
formatted_string = "The set notation is {{1, 2, 3}}.".format()
print(formatted_string)

# Using f-string
formatted_string = f"The set notation is {{1, 2, 3}}."
print(formatted_string)

Output:

The set notation is {1, 2, 3}.
The set notation is {1, 2, 3}.
  • In this example, {{ and }} are used to display { and } inside the string.

8. Advanced String Formatting

You can apply advanced formatting options using both str.format() and f-strings, such as padding with zeros, formatting numbers with commas, and formatting percentages.

Example 1: Padding with Zeros

# Using str.format()
formatted_string = "The number is {:05d}".format(42)
print(formatted_string)

# Using f-string
formatted_string = f"The number is {42:05d}"
print(formatted_string)

Output:

The number is 00042
The number is 00042
  • In this example, {:05d} pads the number with leading zeros to ensure it has at least 5 digits.

Example 2: Formatting Numbers with Commas

large_number = 1000000

# Using str.format()
formatted_string = "The number is {:,}".format(large_number)
print(formatted_string)

# Using f-string
formatted_string = f"The number is {large_number:,}"
print(formatted_string)

Output:

The number is 1,000,000
The number is 1,000,000
  • In this example, {: ,} adds commas as a thousands separator.

Example 3: Formatting Percentages

percentage = 0.75

# Using str.format()
formatted_string = "The success rate is {:.2%}".format(percentage)
print(formatted_string)

# Using f-string
formatted_string = f"The success rate is {percentage:.2%}"
print(formatted_string)

Output:

The success rate is 75.00%
The success rate is 75.00%

 

  • In this example, {:.2%} formats the decimal number as a percentage with 2 decimal places.

Summary of Python String Formatting Methods:

Method Description Example
% Operator Older method, still supported. Uses % for placeholders. “Hello, %s” % name
str.format() Newer method, flexible, uses {} as placeholders. “Hello, {}”.format(name)
f-strings Most modern method (Python 3.6+), uses {} inside literals. f”Hello, {name}”
Advanced Formatting Allows precision, alignment, padding, etc. f”{pi:.2f}”, “{number:,}”, “{:05d}”

Conclusion

Python provides several powerful and flexible ways to format strings, making it easy to work with dynamic data in your programs. In this tutorial, we covered:

  • Three main string formatting methods: the % operator, str.format(), and f-strings.
  • Formatting numbers and strings with precision, alignment, padding, and more.
  • Escaping curly braces in f-strings and str.format().
  • Examples of advanced formatting, such as formatting percentages and adding thousands separators.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More