Mastering String Formatting in Python
Creating well-formatted strings is a daily task in programming, whether for logging, generating reports, or displaying information to users. Python provides several powerful mechanisms for this, each with its own strengths.
1. F-Strings (Formatted String Literals)
Introduced in Python 3.6, f-strings are the modern, preferred way to format strings. They are concise, readable, and fast because they are evaluated at runtime.
Syntax: Start the string with the letter f
or F
and embed expressions inside curly braces {}
.
Pyground
Create a string that introduces a user and their age.
Expected Output:
My name is Ravi and I am 28 years old.
Output:
You can put any valid Python expression inside the braces, including function calls, arithmetic, and object attributes.
Pyground
Use an f-string to display the result of a calculation.
Expected Output:
The total cost is $88.50.
Output:
2. The str.format()
Method
Before f-strings, str.format()
was the standard. It’s more verbose but can be useful in situations where you need to separate the template string from the data, such as in internationalization (i18n) libraries.
Arguments are matched to the {}
placeholders in order.
Pyground
Format a string using positional arguments.
Expected Output:
The quick brown fox jumps over the lazy dog.
Output:
3. The Format Specification Mini-Language
Both f-strings and str.format()
use a powerful mini-language to control how values are presented. The syntax is {field_name:specifier}
.
Common Specifiers
Floating-Point Precision (.nf
)
Control the number of decimal places for floats.
Pyground
Display Pi to 2 and 4 decimal places.
Expected Output:
Pi to 2 decimal places: 3.14 Pi to 4 decimal places: 3.1416
Output:
4. Old Style: The %
Operator
You might see this C-style formatting in older Python code. It’s less flexible than f-strings and str.format()
and is generally not recommended for new code.
Pyground
Use the % operator to format a string.
Expected Output:
User Alice is 30 years old.
Output:
The %
operator has several surprising behaviors and limitations, especially with tuples and dictionaries. Prefer f-strings for all new code.