Difficulty: Beginner
String formatting lets you embed variables and expressions directly inside strings. Python offers several approaches, but f-strings (formatted string literals), introduced in Python 3.6, are the most modern and readable method.
F-strings are created by prefixing a string with f or F. Any expression inside curly braces {} is evaluated at runtime and inserted into the string. You can include variables, arithmetic, function calls, and even conditional expressions inside the braces. For example, f"The sum is {2 + 3}" produces "The sum is 5".
The .format() method is an older but still widely used approach. Curly braces {} act as placeholders that are filled by the arguments passed to .format(). You can use positional arguments like {0}, {1} or keyword arguments like {name}. This method is preferred when you need to reuse a template or when the format string is constructed dynamically.
Format specifications control how values are displayed. Use :.2f for two decimal places, :d for integers, :,d for comma-separated thousands, :>10 for right-alignment in a 10-character field, :<10 for left-alignment, and :^10 for center-alignment. These specifiers work with both f-strings and .format(). The older % formatting (printf-style) uses %s for strings, %d for integers, and %f for floats, but it is less flexible and generally discouraged in modern Python code.
name = "Alice"
age = 30
score = 95.678
print(f"Name: {name}, Age: {age}")
print(f"Next year: {age + 1}")
print(f"Score: {score:.2f}")
print(f"{'Pass' if score > 50 else 'Fail'}")
F-strings evaluate expressions inside {}. The :.2f format specifier rounds to 2 decimal places. Ternary expressions also work inside f-strings.
template = "Hello, {}! You have {} messages."
print(template.format("Bob", 5))
template2 = "Hello, {name}! You are {age} years old."
print(template2.format(name="Carol", age=25))
template3 = "{0} vs {1}: {0} wins!"
print(template3.format("Python", "Java"))
Positional {} arguments are filled in order. Named arguments like {name} are matched by keyword. Indexed arguments like {0} can be reused multiple times.
print(f"{'left':<15}|")
print(f"{'center':^15}|")
print(f"{'right':>15}|")
print(f"{'padded':*^15}|")
< left-aligns, ^ centers, > right-aligns within the given width. A fill character (like *) can precede the alignment symbol.
big_number = 1234567
pi = 3.14159265
print(f"{big_number:,}")
print(f"{pi:.4f}")
print(f"{0.856:.1%}")
print(f"{255:08b}")
:, adds comma separators. :.4f rounds to 4 decimal places. :.1% formats as percentage with 1 decimal. :08b converts to 8-digit binary.
f-strings, format method, percent formatting, alignment, number formatting