What is printf...
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
print(f"...") in Python combines the print() function with f-strings (formatted string literals), introduced in Python 3.6. The f prefix before the string tells Python to evaluate expressions inside curly braces {} and insert their values into the string. F-strings are the fastest and most readable string formatting method in Python, replacing older approaches like % formatting and .format(). This article covers f-string syntax, formatting options, and comparisons with other methods.
Basic F-String Syntax
Everything inside {} is evaluated as a Python expression at runtime. The result is converted to a string and inserted into the output.
Number Formatting
The format spec after : controls width, alignment, precision, and type.
String Formatting
Multiline F-Strings
F-Strings vs Other Methods
F-strings are fastest because they are compiled to efficient bytecode at parse time, while .format() and % require runtime parsing.
Debugging with F-Strings (Python 3.8+)
The = specifier (Python 3.8+) prints both the expression text and its value, which is convenient for quick debugging.
Escaping Braces and Quotes
Common Pitfalls
- Using f-strings before Python 3.6: F-strings are a syntax error in Python 3.5 and earlier. Use
.format()for compatibility with older Python versions. - Backslashes inside f-string expressions:
f"path: {path\n}"is a syntax error. Assign the expression to a variable first:newline = '\n'; f"path: {newline}". - Security with untrusted input: F-strings evaluate arbitrary expressions. Never use
eval(f"...")or construct f-strings from user input. UseTemplatestrings for untrusted data. - Missing the f prefix:
print("Hello, {name}")prints the literal text{name}instead of the variable value. Thefprefix is required for expression evaluation. - Complex expressions reducing readability:
f"{data[key].method(arg1, arg2).attr:.2f}"is hard to read. Extract complex expressions to variables before the f-string.
Summary
print(f"...")combines Python'sprint()with f-string formatting for inline expression evaluation- Use
:inside braces for number formatting:{value:.2f}(decimals),{value:,}(thousands),{value:.1%}(percent) - F-strings are the fastest Python string formatting method — prefer them over
.format()and% - Use
{expr = }(Python 3.8+) for quick debug printing that shows both expression and value - Double braces
{{}}for literal curly braces in the output - Never use f-strings with untrusted input — use
Templatestrings instead

