What Are Format Strings?
Format strings are strings that include placeholders that can be replaced with variable values and expressions at runtime. This makes it easy to create dynamic text output that embeds values or expressions within a string, instead of manually combining text and variables.
Why Use Format Strings?
Using format strings improves:
Readability - text and values appear together clearly
Maintainability - easier to update messages
Flexibility - supports data of different types and expressions
Python supports multiple ways to format strings, but the most common and modern approach is formatted string literals (f-strings). Older approaches like.format()are still useful and widely supported.
1. Formatted String Literals (f-Strings)
Introduced in Python 3.6, f-strings are the preferred way to format strings because they are concise and readable. An f-string starts with the letter f before the opening quote, and expressions inside {} are evaluated at runtime and inserted into the string
Example:
You can also embed expressions and calculations inside {}:
2. The format() Method
The format() method is a flexible approach that works in all Python 3 versions. You include placeholders {} in the string and call .format() with values to inject into those placeholders.
Example:
You can also use named placeholders:
3. Old-Style % Formatting
Python also supports older style formatting using the % operator (printf-style), though it is less common in modern code. For example:
This syntax uses %s as a placeholder for strings.