Last modified: Feb 09, 2025 By Alexander Williams

Python Print Format String: A Beginner's Guide

Formatting strings in Python is essential for creating readable and dynamic outputs. This guide will walk you through the most common methods: f-strings, format(), and %-formatting.

What is String Formatting?

String formatting allows you to insert variables or expressions into a string. It makes your code cleaner and more readable. Python offers multiple ways to format strings.

Using F-Strings

F-strings, introduced in Python 3.6, are the most modern and efficient way to format strings. They are easy to read and write. Simply prefix your string with an f and use curly braces {} to embed expressions.


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


My name is Alice and I am 30 years old.

F-strings are fast and concise. For more details, check out our guide on Understanding F-Strings in Python.

Using the format() Method

The format() method is another way to format strings. It uses placeholders {} and is more flexible than %-formatting. You can pass arguments to format() to replace the placeholders.


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


My name is Bob and I am 25 years old.

You can also use named placeholders for better readability. This method is great for complex string formatting.

Using %-Formatting

%-formatting is the oldest method and is similar to C's printf. It uses % as a placeholder. While it's less readable, it's still used in older codebases.


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


My name is Charlie and I am 35 years old.

This method is less preferred in modern Python but is still useful for compatibility with older versions.

Choosing the Right Method

F-strings are the best choice for most cases due to their simplicity and speed. Use format() for more complex scenarios. Reserve %-formatting for legacy code.

For more advanced string manipulation, explore our guide on Python String Interpolation.

Conclusion

String formatting is a powerful tool in Python. Whether you use f-strings, format(), or %-formatting, each method has its strengths. Start with f-strings for simplicity and efficiency.

For more Python tips, check out our guide on Convert Python String to Datetime.