Nearby lessons
53 of 109Python - String Formatting
Overview
String formatting is used to insert values into strings dynamically and create readable, user-friendly output.
It helps avoid manual string concatenation and keeps output consistent.
Ways to Format Strings
- Using the
%operator - Using the
format()method - Using
f-strings
% Operator
The old-style formatting method uses specifiers such as %s, %d,
and %f.
You can also limit decimal places using syntax like %.2f.
format() Method
format() is a modern and flexible method for string formatting.
It also supports indexed placeholders and alignment controls.
f-Strings
f-strings were introduced in Python 3.6 and provide the cleanest syntax for formatting.
f-strings can also evaluate expressions directly inside the braces.
Common Formatting Features
- Decimal control for floats
- Left, right, and center alignment
- Expression evaluation inside f-strings
- Thousands separators and percentage formatting
These features make formatted output easier to read and present.
Quick Comparison
| Method | Style |
|---|---|
| % operator | Old style |
| format() | Flexible and readable |
| f-string | Modern, clean, and fast |