Skip to main content

How to format a string in Python

How to format a string in Python.

Here is a detailed step-by-step tutorial on how to format a string in Python.

Introduction to String Formatting

String formatting is a way to dynamically insert values into a string. It allows you to create more readable and flexible strings by incorporating variables, numbers, and other data types into the text. Python provides multiple ways to format strings, including the older % operator and the newer str.format() method. In this tutorial, we will focus on the str.format() method, which is considered more versatile and powerful.

Step 1: Basic String Formatting

To start, let's look at the basic syntax of the str.format() method:

formatted_string = "Hello, my name is {}".format(name)

In the above example, {} is a placeholder that will be replaced with the value of the name variable. To assign a value to this placeholder, we use the format() method. This method takes the value we want to insert and places it at the corresponding location in the string.

Here's an example that demonstrates basic string formatting:

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

Output:

My name is Alice and I'm 25 years old

Step 2: Specifying Format Specifiers

Format specifiers allow us to control how values are displayed within the formatted string. They provide options for formatting numbers, floats, dates, and more.

For example, we can specify the number of decimal places for a float using the :.nf format specifier, where n is the desired number of decimal places:

pi = 3.14159
formatted_pi = "The value of pi is {:.2f}".format(pi)
print(formatted_pi)

Output:

The value of pi is 3.14

Here, :.2f specifies that we want the float pi to be displayed with two decimal places.

Step 3: Index-based Formatting

In addition to using placeholders without any explicit index, you can also use index-based placeholders to specify the order of the values being inserted. This allows you to reuse the same value multiple times in a string.

Here's an example:

name = "Alice"
age = 25
formatted_string = "{1} is {0} years old. {1} lives in {2}.".format(age, name, "London")
print(formatted_string)

Output:

Alice is 25 years old. Alice lives in London.

In the above example, the index numbers {0}, {1}, and {2} correspond to the positions of the variables age, name, and the string "London" that we passed to the format() method.

Step 4: Named Arguments Formatting

Another way to format strings is by using named arguments. This can make the code more readable, especially when dealing with a large number of arguments.

Here's an example:

formatted_string = "Welcome, {name}. You have {count} new messages.".format(name="Alice", count=5)
print(formatted_string)

Output:

Welcome, Alice. You have 5 new messages.

In the above example, we used named arguments {name} and {count} within the string and assigned values to them using the format() method.

Step 5: f-strings (Python 3.6+)

Starting from Python 3.6, a new and more concise way to format strings was introduced called f-strings. F-strings allow you to embed expressions inside string literals by prefixing them with the letter f.

Here's an example:

name = "Alice"
age = 25
formatted_string = f"My name is {name} and I'm {age} years old"
print(formatted_string)

Output:

My name is Alice and I'm 25 years old

F-strings provide a more readable and efficient way to format strings, especially when working with complex expressions.

Conclusion

In this tutorial, you learned how to format strings in Python using the str.format() method. You now have the ability to dynamically insert values into strings, control their formatting, and use index-based and named arguments. Additionally, you explored the newer f-string syntax, which simplifies string formatting even further.