Format Strings in Python

String formatting in Python is a powerful way to create dynamic and readable strings by injecting variables into a string template. It enhances the flexibility of your code, making it easier to generate customized outputs based on variable data. Python provides multiple methods for string formatting, each with its unique features and use cases.

Using the format() Method

The format() method allows you to insert variables into placeholders defined by curly braces {} within a string. It is one of the most versatile formatting options, supporting complex expressions and aligning content.

Python
name = "Bob"
age = 25

formatted_str = "My name is {} and I am {} years old.".format(name, age)
print(formatted_str)  # Output: My name is Bob and I am 25 years old.

You can also specify the order of variables, use the same variable multiple times, and format numbers:

Python
# Using positional and keyword arguments
formatted_str = "My name is {0} and I am {1} years old. {0} likes Python.".format(name, age)
print(formatted_str)  # Output: My name is Bob and I am 25 years old. Bob likes Python.

# Formatting numbers
pi = 3.14159
formatted_str = "Pi to two decimal places is {:.2f}".format(pi)
print(formatted_str)  # Output: Pi to two decimal places is 3.14

Using f-Strings (Python 3.6+)

f-Strings, also known as formatted string literals, provide a more concise and readable way to format strings. They allow you to embed expressions directly within string literals by prefixing the string with an f or F.

Python
name = "Carol"
age = 22

# Using f-string
formatted_str = f"My name is {name} and I am {age} years old."
print(formatted_str)  # Output: My name is Carol and I am 22 years old.

f-Strings can include expressions and support complex formatting directly inside the braces:

Python
# Inline calculations and expressions
formatted_str = f"In two years, {name} will be {age + 2} years old."
print(formatted_str)  # Output: In two years, Carol will be 24 years old.

# Formatting numbers within f-strings
pi = 3.14159
formatted_str = f"Pi to three decimal places is {pi:.3f}"
print(formatted_str)  # Output: Pi to three decimal places is 3.142

Using % Formatting

The % formatting method is an older way of formatting strings, inspired by C's printf-style formatting. Although it is less commonly used in new code, it is still supported and found in many Python codebases.

Python
name = "David"
age = 35

formatted_str = "My name is %s and I am %d years old." % (name, age)
print(formatted_str)  # Output: My name is David and I am 35 years old.

With % formatting, you can format strings, integers, floating-point numbers, and other types:

Python
# Formatting a floating-point number
pi = 3.14159
formatted_str = "Pi to four decimal places is %.4f" % pi
print(formatted_str)  # Output: Pi to four decimal places is 3.1416

Advanced Formatting with format() and f-Strings

Both the format() method and f-strings support advanced formatting options, such as alignment, padding, and width specification.

Python
# Aligning text with format()
formatted_str = "{:<10} | {:^10} | {:>10}".format("Left", "Center", "Right")
print(formatted_str)
# Output:
# Left       |   Center   |      Right

# Aligning text with f-strings
formatted_str = f"{"Left":<10} | {"Center":^10} | {"Right":>10}"
print(formatted_str)
# Output:
# Left       |   Center   |      Right

In these examples, << /code> aligns to the left, ^ centers the text, and > aligns to the right. The numbers after the colon specify the width of the field.

Conclusion

String formatting is a vital tool in Python, making your output dynamic, flexible, and readable. Whether you choose to use the format() method, f-strings, or the % operator, understanding these techniques will enable you to write more efficient and cleaner code, especially in scenarios where you need to construct complex strings or output formatted data.