String formatting means inserting values into a string and controlling how those values appear. In modern Python, f-strings are usually the simplest option.
Tested on: Python 3.13.3; kernel 6.14.0-37-generic.
Quick answer: format a string in Python
Use f"{name}" for modern formatting. Use "{}".format(value) for str.format(). Use "%s" % value mainly for older code.
name = "Deepak"
price = 19.99
print(f"Hello {name}")
print("Hello {}".format(name))
print("Price: %.2f" % price)Each line builds a formatted string with a different style. For appending text without full formatting rules, see Append string in Python.
Python string format quick reference
| Task | Use |
|---|---|
| Insert variable | f"Hello {name}" |
| Insert expression | f"Total: {price * qty}" |
| Format integer | f"{num:d}" |
| Format float to 2 decimals | f"{price:.2f}" |
| Add comma separator | f"{num:,}" |
| Format percentage | f"{ratio:.2%}" |
| Left align | f"{text:<10}" |
| Right align | f"{text:>10}" |
| Center align | f"{text:^10}" |
| Zero pad number | f"{num:05d}" |
| Use str.format() | "Hello {}".format(name) |
| Use named placeholders | "Hello {name}".format(name=name) |
| Old integer placeholder | "%d" % num |
| Old string placeholder | "%s" % text |
| Literal braces | f"{{}}" or "{{}}".format() |
What is string formatting in Python?
String formatting inserts values into a string. It can also control width, alignment, padding, decimal places, signs, commas, percentages, and dates. For joining plain text without format specifiers, see Python concatenate strings.
Python has three common styles:
- f-strings — best for most modern code
str.format()— useful for reusable templates- Percent formatting — common in older code
Best way to format strings in modern Python
Use f-strings for most new Python 3.6+ code. They are readable and allow variables and expressions inside braces.
Use str.format() when you need a reusable template string stored separately from the values. Use percent formatting mainly for older code or logging-style patterns you already see in existing projects. When you only need to test whether two formatted values match, compare strings after normalizing case or whitespace if needed.
Python f-string format
Syntax: f"text {value}"
Variables and expressions go inside curly braces. f-strings are evaluated at runtime.
name = "Deepak"
qty = 3
price = 4.50
print(f"Hello {name}")
print(f"Total: {qty * price:.2f}")This should be your default choice in new Python code.
Format variables with f-strings
name = "Deepak"
roll = 4359
subject = "Python"
print(f"Hello {name}, your roll number is {roll}")
print(f"{name} is studying {subject}")Insert strings, integers, and simple expressions directly in the sentence.
Format numbers with f-strings
num = 1234567
price = 19.995
ratio = 0.25
print(f"{num:d}")
print(f"{num:,}")
print(f"{price:.2f}")
print(f"{ratio:.2%}")
print(f"{42:+d}")
print(f"{7:05d}")Common specifiers include d for integers, .2f for two decimal places, , for thousands separators, .2% for percentages, + for explicit signs, and 05d for zero-padded integers.
Format strings with width, padding, and alignment
text = "Python"
num = 42
print(f"|{text:<10}|")
print(f"|{text:>10}|")
print(f"|{text:^10}|")
print(f"|{num:*>8}|")
print(f"|{num:0=8d}|")<left align>right align^center align- A fill character can appear before the alignment symbol, such as
*>or0=
Python str.format() method
Syntax: "Hello {}".format(name)
str.format() inserts values into {} placeholders and returns the formatted string.
name = "Deepak"
roll = 4359
print("Hello {}, your roll number is {}".format(name, roll))
print("Hello {0}, your roll number is {1}".format(name, roll))
print("Hello {name}, your roll number is {num}".format(name=name, num=roll))The same format specifiers after the colon work here too: {price:.2f}, {text:<10}, and {num:,}.
Positional and named placeholders with format()
{}uses argument order from.format(){0}and{1}use index positions{name}uses keyword arguments
print("{1} before {0}".format("second", "first"))
print("{name} scored {score:.1f}".format(name="Alex", score=88.5))A missing index raises IndexError. A missing keyword raises KeyError.
f-string vs str.format()
| Feature | f-string | str.format() |
|---|---|---|
| Python version | 3.6+ | 2.6+ / 3.x |
| Readability | Usually best | Good |
| Reusable template | Less ideal | Better |
| Variables inline | Yes | No, passed to format() |
| Supports format specifiers | Yes | Yes |
| Best for | Modern application code | Templates, older compatibility |
Percent formatting in Python
Percent formatting is old-style formatting. It uses %s, %d, %f, and other placeholders with the % operator. You still see it in older codebases.
Python documents printf-style string formatting. It is not the recommended choice for new code, but it is not removed.
name = "Deepak"
drink = "coffee"
price = 3
message = "Hey %s, this %s costs $%d." % (name, drink, price)
print(message)What does %d mean in Python?
%dmeans signed decimal integer%smeans string%fmeans floating-point number%%prints a literal percent sign
age = 32
text = "Python"
value = 19.99
print("Age: %d" % age)
print("Lang: %s" % text)
print("Price: %.2f" % value)
print("Done 100%%")Use %d only with integer values.
Common percent formatting placeholders
| Placeholder | Meaning |
|---|---|
%s |
String using str() |
%r |
String using repr() |
%d |
Decimal integer |
%f |
Floating-point number |
%.2f |
Float with 2 decimal places |
%x |
Hexadecimal lowercase |
%% |
Literal percent sign |
Format decimal places
Formatting controls display output. It does not change the stored numeric value.
value = 3.14159
print(f"{value:.2f}")
print("{:.2f}".format(value))
print("%.2f" % value)
print(value)All three formatted outputs show 3.14, while the original variable still holds the full float.
Format percentages
ratio = 0.25
print(f"{ratio:.2%}")
print("{:.2%}".format(ratio))0.25 displays as 25.00%. Useful for rates, ratios, and progress values.
Format dates and times
Use datetime objects with format codes inside braces:
from datetime import datetime
today = datetime(2026, 6, 23, 15, 30)
print(f"{today:%Y-%m-%d}")
print(f"{today:%d/%m/%Y %H:%M}")
print("{:%Y-%m-%d}".format(today))See Python datetime for more date and time formatting.
Escape braces in formatted strings
Use double braces when you need literal { or } in the output.
count = 3
print(f"Use {{ and }} to show braces. Count = {count}")
print("Literal braces: {{}}".format())This avoids confusing the formatter with placeholder syntax.
Which Python string formatting method should you use?
| Situation | Recommended |
|---|---|
| New Python 3.6+ code | f-string |
| Formatting variables in a sentence | f-string |
| Formatting numbers | f-string |
| Reusable template string | str.format() |
| Older Python compatibility | str.format() or % |
| Reading old code | Learn % formatting |
| Logging messages | Prefer logging placeholders over manual string building when possible |
Summary
Use f-strings for most modern Python string formatting. Use str.format() for templates and older compatibility. Use percent formatting mainly when reading or maintaining old code. Use format specifiers for width, alignment, padding, decimals, percentages, and dates. Remember that %d means decimal integer in old percent-style formatting. To split formatted output into fields later, see Python split string.
References
- Python formatted string literals (f-strings)
- Python
str.format()documentation - Python format specification mini-language
- Python printf-style string formatting

