Python String Format

Learn Python string formatting using f-strings, str.format(), and percent formatting. See examples for variables, numbers, decimal precision, padding, alignment, percentages, dates, and %d meaning in Python.

Published

Updated

Read time 6 min read

Reviewed byDeepak Prasad

Python String Format

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.

python
name = "Deepak"
price = 19.99

print(f"Hello {name}")
print("Hello {}".format(name))
print("Price: %.2f" % price)
Output

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.

python
name = "Deepak"
qty = 3
price = 4.50

print(f"Hello {name}")
print(f"Total: {qty * price:.2f}")
Output

This should be your default choice in new Python code.


Format variables with f-strings

python
name = "Deepak"
roll = 4359
subject = "Python"

print(f"Hello {name}, your roll number is {roll}")
print(f"{name} is studying {subject}")
Output

Insert strings, integers, and simple expressions directly in the sentence.


Format numbers with f-strings

python
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}")
Output

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

python
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}|")
Output
  • < left align
  • > right align
  • ^ center align
  • A fill character can appear before the alignment symbol, such as *> or 0=

Python str.format() method

Syntax: "Hello {}".format(name)

str.format() inserts values into {} placeholders and returns the formatted string.

python
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))
Output

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
python
print("{1} before {0}".format("second", "first"))
print("{name} scored {score:.1f}".format(name="Alex", score=88.5))
Output

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.

python
name = "Deepak"
drink = "coffee"
price = 3

message = "Hey %s, this %s costs $%d." % (name, drink, price)
print(message)
Output

What does %d mean in Python?

  • %d means signed decimal integer
  • %s means string
  • %f means floating-point number
  • %% prints a literal percent sign
python
age = 32
text = "Python"
value = 19.99

print("Age: %d" % age)
print("Lang: %s" % text)
print("Price: %.2f" % value)
print("Done 100%%")
Output

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.

python
value = 3.14159

print(f"{value:.2f}")
print("{:.2f}".format(value))
print("%.2f" % value)
print(value)
Output

All three formatted outputs show 3.14, while the original variable still holds the full float.


Format percentages

python
ratio = 0.25

print(f"{ratio:.2%}")
print("{:.2%}".format(ratio))
Output

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:

python
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))
Output

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.

python
count = 3

print(f"Use {{ and }} to show braces. Count = {count}")
print("Literal braces: {{}}".format())
Output

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


Frequently Asked Questions

1. What is the best way to format strings in Python?

Use f-strings in Python 3.6 and later for most new code. They are readable and support variables, expressions, and format specifiers inside braces.

2. What is the difference between f-strings and str.format()?

f-strings embed values directly in the string literal. str.format() inserts values into {} placeholders and works better for reusable template strings.

3. What does %d mean in Python?

%d means signed decimal integer in old percent-style formatting. It is used with the % operator, for example "Age: %d" % age.

4. Is percent formatting deprecated in Python?

No. It is old-style or legacy formatting, but Python still documents printf-style string formatting for reading and maintaining older code.

5. How do you format a float to two decimal places in Python?

Use f"{value:.2f}" in modern code, "{:.2f}".format(value) with str.format(), or "%.2f" % value in percent-style formatting.

6. How do you escape literal braces in formatted strings?

Use double braces {{ and }} in both f-strings and str.format() when you want literal curly braces in the output.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …