PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Basics » Python f-Strings and String Formatting: The Complete Guide

Python f-Strings and String Formatting: The Complete Guide

Updated on: December 4, 2026 | Leave a Comment

String formatting means building a string that includes values from your program, such as a name, a price, or today’s date. Python offers several ways to do it, but f-strings (formatted string literals, added in Python 3.6) are the fastest, the most readable, and the one you should use by default.

In this tutorial, you’ll learn how f-strings work, how to format numbers, dates, and text with the format specification mini-language, how to debug with f-strings, and when the older str.format(), % operator, and Template strings are still useful.

Key terms used in this article:

  • f-string: A string literal prefixed with f or F that can contain expressions inside curly braces, such as f"Hello, {name}".
  • Replacement field: The {...} part of an f-string. Python replaces it with the value of the expression inside.
  • Format specifier: Instructions after a colon inside the braces that control how a value looks, such as {price:.2f}.
  • Interpolation: Inserting values into a string.

Table of contents

  • Why string formatting matters
  • f-string basics
    • Expressions inside f-strings
    • Multi-line f-strings
    • Quotes and backslashes
    • Printing literal braces
  • Formatting numbers
    • Decimal places
    • Thousands separators
    • Percentages
    • Scientific notation and general format
    • Sign, padding with zeros, and width
    • Binary, octal, and hexadecimal
  • Aligning text and building tables
    • Dynamic width and precision
  • The format specification mini-language
  • Formatting dates and times
  • Debugging with the = specifier
  • Conversion flags: !s, !r, and !a
  • Formatting your own objects
  • The str.format() method
  • The % operator (old style)
  • Template strings
  • Template string literals (t-strings) in Python 3.14
  • Which formatting method should you use?
  • Common mistakes
  • Practice exercises
  • Summary

Why string formatting matters

Without formatting, you’d have to join strings with + and convert every number with str():

name = "Jessa"
age = 28

# Clumsy: manual conversion and concatenation
print("My name is " + name + " and I am " + str(age) + " years old.")

# Clean: f-string
print(f"My name is {name} and I am {age} years old.")Code language: Python (python)

Output:

My name is Jessa and I am 28 years old.
My name is Jessa and I am 28 years old.

The f-string version is shorter, easier to read, and converts values to text automatically.

f-string basics

Put the letter f (or F) before the opening quote, and write any variable or expression inside curly braces {}:

city = "Paris"
temperature = 21.5

message = f"It is {temperature} degrees in {city}."
print(message)
print(F"Uppercase F works too: {city}")Code language: Python (python)

Output:

It is 21.5 degrees in Paris.
Uppercase F works too: Paris

f-strings work with single quotes, double quotes, and triple quotes.

Expressions inside f-strings

The braces can hold any valid Python expression: arithmetic, function calls, method calls, indexing, and even conditional expressions.

a, b = 7, 3
items = ["pen", "book", "lamp"]
user = {"name": "Kelly", "role": "admin"}

print(f"{a} + {b} = {a + b}")
print(f"Number of items: {len(items)}")
print(f"First item in uppercase: {items[0].upper()}")
print(f"User: {user['name']} ({user['role']})")
print(f"{a} is {'odd' if a % 2 else 'even'}")Code language: Python (python)

Output:

7 + 3 = 10
Number of items: 3
First item in uppercase: PEN
User: Kelly (admin)
7 is odd

Keep the expressions short. If the logic gets complicated, calculate the value in a variable first, then insert the variable.

Multi-line f-strings

Use triple quotes for a multi-line f-string, or put several f-strings inside parentheses. Python joins adjacent string literals automatically:

name = "Emma"
total = 149.5

receipt = f"""
Customer: {name}
Total:    ${total}
"""
print(receipt)

summary = (
    f"Customer {name} "
    f"spent ${total} "
    f"today."
)
print(summary)Code language: Python (python)

Output:

Customer: Emma
Total:    $149.5

Customer Emma spent $149.5 today.

Quotes and backslashes

Use a different quote type inside the braces than the one that surrounds the f-string, for example single quotes inside a double-quoted f-string. Since Python 3.12, you can reuse the same quote type and use backslashes inside the expression part, but different quotes keep your code compatible with older versions.

data = {"lang": "Python"}
print(f"Language: {data['lang']}")

words = ["one", "two", "three"]
newline = "\n"
print(f"Words:{newline}{newline.join(words)}")Code language: Python (python)

Output:

Language: Python
Words:
one
two
three

Printing literal braces

To show a curly brace in the output, double it: {{ prints { and }} prints }.

value = 42
print(f"{{value}} is replaced by {value}")
print(f"Set literal: {{{value}}}")Code language: Python (python)

Output:

{value} is replaced by 42
Set literal: {42}

Formatting numbers

Add a colon after the expression, followed by a format specifier. The specifier controls decimals, width, separators, signs, and number systems.

Decimal places

.Nf rounds a number to N digits after the decimal point:

pi = 3.14159265
price = 49.5

print(f"{pi:.2f}")
print(f"{pi:.4f}")
print(f"${price:.2f}")
print(f"{10:.1f}")  # integers can be shown as floatsCode language: Python (python)

Output:

3.14
3.1416
$49.50
10.0

Thousands separators

Use , or _ to group digits in thousands:

population = 8_100_000_000
revenue = 1234567.891

print(f"{population:,}")
print(f"{population:_}")
print(f"{revenue:,.2f}")Code language: Python (python)

Output:

8,100,000,000
8_100_000_000
1,234,567.89

Percentages

% multiplies the number by 100 and adds a percent sign:

ratio = 0.8567
print(f"{ratio:%}")
print(f"{ratio:.1%}")
print(f"Completion: {17 / 20:.0%}")Code language: Python (python)

Output:

85.670000%
85.7%
Completion: 85%

Scientific notation and general format

distance = 149_600_000_000  # meters from Earth to the Sun
tiny = 0.000012345

print(f"{distance:e}")
print(f"{distance:.2e}")
print(f"{tiny:.3e}")
print(f"{tiny:g}")  # g picks fixed or scientific automaticallyCode language: Python (python)

Output:

1.496000e+11
1.50e+11
1.234e-05
1.2345e-05

Sign, padding with zeros, and width

n = 42
print(f"{n:+}")      # always show the sign
print(f"{-n:+}")
print(f"{n: }")      # space for positive numbers
print(f"{n:05}")     # pad with zeros to width 5
print(f"{7:03d}")    # common for IDs and file names
print(f"{3.5:08.3f}")Code language: Python (python)

Output:

+42
-42
 42
00042
007
0003.500

Binary, octal, and hexadecimal

n = 255
print(f"{n:b}")    # binary
print(f"{n:o}")    # octal
print(f"{n:x}")    # hex, lowercase
print(f"{n:X}")    # hex, uppercase
print(f"{n:#x}")   # with 0x prefix
print(f"{n:#010b}")  # prefix, zero-padded to width 10
print(f"{5:08b}")  # 8-bit binaryCode language: Python (python)

Output:

11111111
377
ff
FF
0xff
0b11111111
00000101

Aligning text and building tables

Set a width and an alignment character to line up text in columns:

SpecifierMeaning
<Left-align (default for strings)
>Right-align (default for numbers)
^Center
=Put padding after the sign, as in -0042

You can also put a fill character before the alignment symbol:

word = "Python"
print(f"|{word:<12}|")
print(f"|{word:>12}|")
print(f"|{word:^12}|")
print(f"|{word:*^12}|")
print(f"|{word:-<12}|")Code language: Python (python)

Output:

|Python      |
|      Python|
|   Python   |
|***Python***|
|Python------|

Combining width and precision makes neat tables:

products = [("Keyboard", 3, 49.99), ("Mouse", 12, 19.5), ("Monitor", 1, 229.0)]

print(f"{'Item':<10}{'Qty':>5}{'Price':>10}")
print("-" * 25)
for name, qty, price in products:
    print(f"{name:<10}{qty:>5}{price:>10.2f}")Code language: Python (python)

Output:

Item        Qty     Price
-------------------------
Keyboard      3     49.99
Mouse        12     19.50
Monitor       1    229.00

Dynamic width and precision

You can put another replacement field inside the format specifier to set the width or precision at runtime:

value = 3.14159
width = 10
decimals = 3
print(f"|{value:{width}.{decimals}f}|")

for d in range(1, 4):
    print(f"{value:.{d}f}")Code language: Python (python)

Output:

|     3.142|
3.1
3.14
3.142

The format specification mini-language

Every format specifier follows the same pattern. Each part is optional, but the order is fixed:

[[fill]align][sign][z][#][0][width][grouping][.precision][type]
PartExamplesWhat it does
fill*, -, 0Character used for padding
align<, >, ^, =Alignment within the width
sign+, -, spaceHow to show the sign
zzTurns -0.0 into 0.0 after rounding (3.11+)
##Adds 0b, 0o, 0x prefixes
00Zero-pads numbers
width10Minimum total width
grouping,, _Thousands separator
precision.2Digits after the decimal point, or maximum length for strings
typef, e, g, %, d, b, o, x, X, sPresentation type

Precision also truncates strings:

title = "Structural Pattern Matching"
print(f"{title:.10}")
print(f"{title:.10}...")Code language: Python (python)

Output:

Structural
Structural...

Formatting dates and times

datetime objects accept strftime() codes directly inside an f-string:

from datetime import datetime

moment = datetime(2026, 12, 4, 14, 30, 5)

print(f"{moment:%Y-%m-%d}")
print(f"{moment:%d/%m/%Y %H:%M}")
print(f"{moment:%A, %B %d, %Y}")
print(f"{moment:%I:%M %p}")Code language: Python (python)

Output:

2026-12-04
04/12/2026 14:30
Friday, December 04, 2026
02:30 PM
CodeMeaningExample
%Y4-digit year2026
%mMonth as number12
%dDay of month04
%B / %bMonth name, full / shortDecember / Dec
%A / %aWeekday, full / shortFriday / Fri
%H / %IHour, 24-hour / 12-hour14 / 02
%M, %SMinutes, seconds30, 05
%pAM or PMPM

Debugging with the = specifier

Add = after an expression (Python 3.8+) to print both the expression and its value. It’s perfect for quick debugging:

x = 10
y = 3
name = "Jessa"

print(f"{x=}")
print(f"{x * y=}")
print(f"{name=}")
print(f"{x / y=:.2f}")
print(f"{x = }")  # spaces are kept in the outputCode language: Python (python)

Output:

x=10
x * y=30
name='Jessa'
x / y=3.33
x = 10

Conversion flags: !s, !r, and !a

By default, f-strings use str() to convert a value. Conversion flags let you choose:

FlagCallsUse it for
!sstr()Readable output (the default)
!rrepr()Unambiguous output, such as strings with quotes
!aascii()Escaping non-ASCII characters
text = "café"
print(f"{text!s}")
print(f"{text!r}")
print(f"{text!a}")Code language: Python (python)

Output:

café
'café'
'caf\xe9'

!r is useful for spotting hidden spaces or empty strings in your data: f"{value!r}" shows ' ' instead of blank output.

Formatting your own objects

f-strings call an object’s __format__() method, which receives the format specifier. You can implement it in your own classes:

class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius

    def __format__(self, spec):
        if spec == "F":
            return f"{self.celsius * 9 / 5 + 32:.1f}°F"
        return f"{self.celsius:.1f}°C"


t = Temperature(21.5)
print(f"Today: {t}")
print(f"Today: {t:F}")Code language: Python (python)

Output:

Today: 21.5°C
Today: 70.7°F

The str.format() method

Before f-strings, str.format() was the main way to format strings. It uses the same format specifiers, but the values are passed as arguments:

print("Hello, {}! You are {} years old.".format("Jessa", 28))
print("{0} vs {1}, then {1} vs {0}".format("A", "B"))
print("{name} scored {score:.1f}".format(name="Kelly", score=91.256))

person = {"name": "Emma", "city": "Rome"}
print("{name} lives in {city}".format(**person))Code language: Python (python)

Output:

Hello, Jessa! You are 28 years old.
A vs B, then B vs A
Kelly scored 91.3
Emma lives in Rome

str.format() is still the right tool when the template is created before the values exist, for example when templates are stored in a file, a database, or a settings dictionary:

TEMPLATES = {
    "welcome": "Welcome, {user}! You have {count} new messages.",
}

print(TEMPLATES["welcome"].format(user="Jessa", count=5))Code language: Python (python)

Output:

Welcome, Jessa! You have 5 new messages.

The % operator (old style)

The % operator is the oldest formatting style. You’ll still see it in older code and in the logging module:

name = "Jessa"
balance = 1520.758

print("Hello, %s!" % name)
print("%s has $%.2f" % (name, balance))
print("%-10s|%8.1f|" % (name, balance))
print("%(name)s has %(count)d items" % {"name": "Kelly", "count": 3})Code language: Python (python)

Output:

Hello, Jessa!
Jessa has $1520.76
Jessa     |  1520.8|
Kelly has 3 items
PlaceholderType
%sString (any object, via str())
%dInteger
%fFloat (%.2f for 2 decimals)
%xHexadecimal
%%A literal percent sign

Template strings

string.Template uses $name placeholders and can’t run expressions, which makes it safer when the template comes from users:

from string import Template

template = Template("Hi $name, your order #$order_id has shipped.")
print(template.substitute(name="Jessa", order_id=1042))

# safe_substitute leaves missing placeholders unchanged
print(template.safe_substitute(name="Kelly"))Code language: Python (python)

Output:

Hi Jessa, your order #1042 has shipped.
Hi Kelly, your order #$order_id has shipped.

Never call .format() on a string supplied by a user. A malicious template can read attributes of the objects you pass in. Use Template for user-supplied templates.

Template string literals (t-strings) in Python 3.14

Python 3.14 adds t-strings, written with a t prefix. They look like f-strings, but instead of producing a str, they produce a Template object that keeps the static text and the interpolated values separate. Libraries can then process the values safely, for example by escaping HTML or SQL:

# Requires Python 3.14+
from string.templatelib import Template

name = "<b>Jessa</b>"
template = t"Hello, {name}!"

print(type(template))  # <class 'string.templatelib.Template'>
print(template.strings)  # ('Hello, ', '!')
print(template.values)   # ('<b>Jessa</b>',)Code language: Python (python)

For everyday string building, keep using f-strings. t-strings are meant for libraries that need to inspect or sanitize values.

Which formatting method should you use?

MethodExampleWhen to use
f-stringf"{name} is {age}"Default choice for almost all code
str.format()"{} is {}".format(name, age)Templates defined before the values exist
% operator"%s is %d" % (name, age)Legacy code and logging calls
TemplateTemplate("$name").substitute(...)Templates provided by users

f-strings are also the fastest, because Python compiles them into efficient bytecode instead of parsing a template at runtime.

Common mistakes

  • Forgetting the f prefix. "Hello, {name}" prints the braces literally.
  • Using the wrong format type. f"{'abc':.2f}" raises ValueError: Unknown format code 'f' for object of type 'str'. Convert text to a number first with float().
  • Using f-strings in logging calls. Write logging.info("User %s logged in", user) so the message is only built when it’s actually logged.
  • Expecting rounding to always go up. f"{2.675:.2f}" gives 2.67, because 2.675 can’t be stored exactly as a float. Use the decimal module for money.
name = "Jessa"
print("Hello, {name}")   # missing f
print(f"Hello, {name}")
print(f"{2.675:.2f}")Code language: Python (python)

Output:

Hello, {name}
Hello, Jessa
2.67

Practice exercises

Exercise 1: Print a price list where item names are left-aligned in 12 characters and prices are right-aligned with 2 decimals in 8 characters.

menu = {"Coffee": 3.5, "Sandwich": 7.25, "Cake": 4}

for item, price in menu.items():
    print(f"{item:<12}{price:>8.2f}")Code language: Python (python)

Output:

Coffee          3.50
Sandwich        7.25
Cake            4.00

Exercise 2: Show a progress message such as Downloaded 45 of 120 files (37.5%).

done, total = 45, 120
print(f"Downloaded {done} of {total} files ({done / total:.1%})")Code language: Python (python)

Output:

Downloaded 45 of 120 files (37.5%)

Exercise 3: Print the numbers 0 to 5 as 4-digit binary, padded with zeros.

for n in range(6):
    print(f"{n:>2} -> {n:04b}")Code language: Python (python)

Output:

 0 -> 0000
 1 -> 0001
 2 -> 0010
 3 -> 0011
 4 -> 0100
 5 -> 0101

Summary

  • Prefix a string with f and put expressions in {} to build strings quickly and readably.
  • Add a format specifier after a colon: .2f for decimals, , for thousands, % for percentages, >10 for alignment, 05 for zero padding, and b/x for binary and hex.
  • Format dates with strftime codes such as {now:%Y-%m-%d}.
  • Use {expr=} to debug and !r to see the exact representation of a value.
  • Use str.format() for templates defined in advance, % only in legacy code and logging, and Template for user-supplied templates.

Also, See:

  • Strings in Python: A Complete Guide
  • Python String Methods
  • Python Input and Output Exercise
  • Python String Exercises

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com