String formatting in Python

Updated: April 24th, 2023, 10:44:06 IST
Published: April 24th, 2023
String formatting in Python
Title: String formatting in Python

String formatting is a very important concept in Python. It allows you to create dynamic strings by inserting values into placeholders. In this post, we will discuss different ways of performing string formatting in Python with examples.

There are four different ways to use string formatting in Python:

  1. Formatting with % Operator
  2. Formatting with format() string method
  3. Formatting with string literals, called f-strings
  4. Formatting with String Template Class
  5. Formatting with center() string method

1. Formatting with % Operator

The % operator is one of the oldest ways of formatting strings in Python. It works by inserting values into a string using placeholders, represented by the % sign. Here is an example:

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

Output:

My name is Alice and I am 25 years old.

In the above example, %s is a placeholder for a string, while %d is a placeholder for a decimal integer. The values to be inserted are passed as a tuple in the order they appear in the string.

2. Formatting with format() string method

The format() string method is a newer and more versatile way of formatting strings in Python. It works by replacing placeholders in a string with values. Here is an example:

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

Output:

My name is Alice and I am 25 years old.

In the above example, {} are placeholders for the values to be inserted. The values are passed as arguments to the format() method in the order they appear in the string.

You can also use named placeholders and positional placeholders with the format() method. Here is an example:

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

Output:

My name is Alice and I am 25 years old.

In the above example, the placeholders are named, and the values are passed as keyword arguments to the format() method.

name = "Alice"
age = 25
print("My name is {0} and I am {1} years old.".format(name, age))

Output:

My name is Alice and I am 25 years old.

In the above example, the placeholders are positional, and the values are passed as positional arguments to the format() method.

3. Formatting with string literals, called f-strings

f-strings are a new way of formatting strings in Python. They work by embedding expressions inside curly braces within a string. Here is an example:

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

Output:

My name is Alice and I am 25 years old.

In the above example, the expressions inside the curly braces are evaluated at runtime and their values are inserted into the string.

4. Formatting with String Template Class

The String Template class provides a simpler syntax for string formatting in Python. It works by replacing placeholders in a string with values. Here is an example:

from string import Template

name = "Alice"
age = 25
template = Template("My name is $name and I am $age years old.")
print(template.substitute(name=name, age=age))

Output:

My name is Alice and I am 25 years old.

In the above example, the placeholders are represented by $ signs. The values are passed as keyword arguments to the substitute() method.

5. Formatting with center() string method

The center() method is used to center-align a string within a specified width. Here is an example:

name = "Alice"
age = 25
print(name.center(20, "-"))
print(str(age).center(20, "-"))

Output:

------Alice-------
--------25---------

In the above example, the center() method is used to center-align the string within a width of 20 characters. The second argument to the method is the fill character, which is used to fill the remaining space.

Example: Formatting string using Template Class

from string import Template

# Create a template string
template_str = "Hello, $name! Your balance is $balance."

# Create a Template object
template = Template(template_str)

# Substitute variables with values
formatted_str = template.substitute(name="Alice", balance="$1000")

# Print the formatted string
print(formatted_str)

Output:

Hello, Alice! Your balance is $1000.

In the above example, we create a template string containing variables denoted by a $ sign. We then create a Template object and use the substitute() method to substitute the variables with actual values. The resulting string is stored in formatted_str and printed to the console.

Note that if we had used the format() method instead, we would need to use curly braces {} to denote the variables. Here's an example:

# Using format() method
formatted_str = "Hello, {}! Your balance is {}.".format("Alice", "$1000")
print(formatted_str)

Output:

Hello, Alice! Your balance is $1000.

As you can see, the Template class provides an alternative way of formatting strings, especially when the formatting is based on a template.

Conclusion

In this post, we have discussed different ways of performing string formatting in Python. We started with the oldest method using the % operator, and then moved on to the newer and more versatile format() method. We also explored the new f-strings, which provide a simpler syntax for string formatting. Additionally, we covered the String Template class and the center() method for special formatting needs.

It is important to choose the appropriate string formatting method based on the requirements of your project. Each method has its own advantages and disadvantages. The % operator is useful for simple string formatting tasks, while the format() method provides more flexibility and supports a wider range of data types. f-strings are the most recent and popular way of formatting strings in Python, providing a simpler syntax and better readability. The String Template class is useful when the formatting is based on a template, and the center() method is useful when center-aligning a string is required.