Python F-Strings
F-strings (formatted string literals) were introduced in Python 3.6 and are now the recommended and most efficient way to format strings in Python.
Before Python 3.6, developers mainly used the
format()
method or string concatenation, which was more verbose and harder to read.
What Are F-Strings?
An f-string lets you embed expressions directly inside string literals. To
create an f-string, prefix the string with the letter
f.
Example: Basic F-String
Using Placeholders in F-Strings
Values are inserted into an f-string using curly braces
{}. Inside
these braces, you can place:
- Variables
- Calculations
- Function calls
- Formatting modifiers
Example: Insert a Variable
Formatting Values with Modifiers
You can control how values appear using formatting modifiers. Modifiers are
added after a colon
: inside the
placeholder.
Example: Limit Decimal Places
Example: Format a Value Directly
Performing Operations in F-Strings
Python expressions can be evaluated directly inside placeholders.
Example: Arithmetic Operation
Example: Calculation Using Variables
Conditional Logic Inside F-Strings
You can use conditional expressions (if...else) within placeholders.
Example: Conditional Output
Calling Functions in F-Strings
Both built-in and user-defined functions can be executed inside f-strings.
Example: Built-in Function
Example: User-Defined Function
Advanced Formatting Options
Example: Thousand Separator
Example: Percentage Format
Common Formatting Types
| Type | Description |
|---|---|
<
|
Left align |
>
|
Right align |
^
|
Center align |
+
|
Show sign |
,
|
Thousand separator |
_
|
Underscore separator |
b
|
Binary |
d
|
Decimal |
f
|
Fixed-point |
e
|
Scientific |
o
|
Octal |
x / X
|
Hexadecimal |
%
|
Percentage |
String Formatting Using format()
Before f-strings, the
format()
method was commonly used. Although still supported, it is less readable and
slower than f-strings.
