
Python
Master all three formatting methods, advanced format specifications, and performance optimization.
F-strings are the modern standardβfast, readable, and powerful.
# Basic f-strings
name = "Alice"
age = 30
print(f"Hello {name}, you are {age} years old")
# Expressions inside f-strings
x, y = 10, 20
print(f"Sum: {x + y}, Product: {x * y}")
# Format specifications
value = 3.14159
print(f"{value:.2f}") # 3.14 (2 decimal places)
print(f"{value:>10.2f}") # " 3.14" (right-aligned, 10 chars)
print(f"{value:<10.2f}") # "3.14 " (left-aligned)
print(f"{value:^10.2f}") # " 3.14 " (centered)
# Number formatting
num = 1234567
print(f"{num:,}") # 1,234,567 (with commas)
print(f"{num:_}") # 1_234_567 (with underscores)
print(f"{num:e}") # 1.234567e+06 (scientific)
# Binary, octal, hex
print(f"{255:b}") # 11111111 (binary)
print(f"{255:o}") # 377 (octal)
print(f"{255:x}") # ff (hex lowercase)
print(f"{255:X}") # FF (hex uppercase)Performance tip: F-strings are evaluated at runtime and are the fastest method.
.format() is more verbose but works in older Python versions.
# Positional arguments
print("{0} {1} {2}".format("a", "b", "c"))
# Named arguments
print("{name} is {age}".format(name="Bob", age=25))
# Mixed arguments
print("{0} is {age} years old".format("Bob", age=25))
# Format specifications
print("{:.2f}".format(3.14159)) # 3.14
print("{:>10}".format("right")) # " right"
print("{:*^10}".format("center")) # "**center**"
# Accessing object attributes
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Charlie", 35)
print("{p.name} is {p.age}".format(p=p))
# Dictionary unpacking
data = {"name": "Diana", "age": 28}
print("{name} is {age}".format(**data))
# Precision for floats
print("{:.3f}".format(1/3)) # 0.333Legacy formatting method, still used in some codebases.
# Basic formatting
print("Hello %s" % "World")
# Multiple values (use tuple)
print("%s is %d years old" % ("Eve", 32))
# Type conversions
print("Float: %.2f" % 3.14159)
print("Integer: %d" % 42.9)
print("Octal: %o, Hex: %x" % (255, 255))
# Width and precision
print("%10s" % "right") # " right"
print("%-10s" % "left") # "left "
print("%08d" % 42) # "00000042"
print("%.3f" % (1/3)) # "0.333"
# Named placeholders (dictionary)
data = {"name": "Frank", "age": 40}
print("%(name)s is %(age)d" % data)All methods support the same format spec:
{value:[[fill]align][sign][#][0][width][grouping_option][.precision][type]}value = 42.5
# Fill and alignment
print(f"{value:*^10}") # "***42.5***" (center with asterisks)
print(f"{value:0>10}") # "0000042.5" (right-align with zeros)
# Sign options
print(f"{value:+}") # "+42.5" (always show sign)
print(f"{value: }") # " 42.5" (space for positive)
print(f"{-value:+}") # "-42.5"
# Alternate form
print(f"{255:#x}") # "0xff" (with prefix)
print(f"{255:#b}") # "0b11111111"
# Grouping
print(f"{1000000:,}") # "1,000,000"
print(f"{1000000:_}") # "1_000_000"
# Type conversion
print(f"{42!s}") # "42" (str())
print(f"{42!r}") # "42" (repr())
print(f"{3.14!a}") # "3.14" (ascii())import timeit
# Time different methods
setup = """
name = "Alice"
age = 30
"""
t1 = timeit.timeit('f"Hello {name}, age {age}"', setup) # Fastest
t2 = timeit.timeit('"Hello {}, age {}".format(name, age)', setup)
t3 = timeit.timeit('"Hello %s, age %d" % (name, age)', setup)
print(f"f-string: {t1:.4f}")
print(f".format(): {t2:.4f}")
print(f"% formatting: {t3:.4f}")
# f-strings ~30% faster than .format()
# % formatting slowest# β Use f-strings for modern code (Python 3.6+)
name = "Bob"
print(f"Hello {name}")
# β Use .format() for backward compatibility
print("Hello {}".format(name))
# β Avoid % formatting (use only if required by legacy code)
# print("Hello %s" % name)
# β Use f-string expressions for readability
x, y = 10, 20
print(f"Sum: {x + y}")
# β Avoid complex expressions in format strings
# print(f"{[x*2 for x in range(10)]}") # Harder to read
# β Use custom __format__ for complex types
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __format__(self, spec):
if spec == "polar":
import math
r = (self.x**2 + self.y**2)**0.5
theta = math.atan2(self.y, self.x)
return f"r={r:.2f}, ΞΈ={theta:.2f}"
return f"({self.x}, {self.y})"
v = Vector(3, 4)
print(f"Cartesian: {v}") # (3, 4)
print(f"Polar: {v:polar}") # r=5.00, ΞΈ=0.93| Method | Use Case | Speed |
|---|---|---|
| F-strings | General use (Python 3.6+) | β Fastest |
| .format() | Backward compatibility | β οΈ ~30% slower |
| % formatting | Legacy code only | β Slowest |
Master Booleans and None for advanced logical operations.
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep β’ Build Real β’ Verify Skills β’ Launch Forward