Python f-strings and String Formatting: A Complete Guide
F-strings are not just a shorter syntax. They support expressions, formatting specs, and debugging output. Here is everything I use. F-strings, introduced in Python 3.6, are the most readable way to format strings in Python. They replaced my use of .format() and the older percent formatting almost entirely. But f-strings are more than a shorter syntax. they support inline expressions, format specifications, and a debugging mode that I use daily. Basic F-string Syntax An f-string is a string prefixed with f or F . Expressions inside curly braces are evaluated and inserted into the string. The expressions can be variables, arithmetic, function calls, or any valid Python expression. name = 'Alice' version = 3.12 message = f'Hello {name}, running Python {version}' # 'Hello Alice, running Python 3.12' # Expressions work too print(f'Result: {2 ** 10}') # Result: 1024 print(f'Upper: {name.upper()}') # Upper: ALICE Unlike .format() , the expression is evaluated at the location where it appears, so there is no mismatch between placeholders and arguments. This eliminates a common source of bugs. Format Specifications After the expression, a colon introduces a format specification. This controls alignment, width, precision, and type.…