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
Output:
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
Output:
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
Output:
Example: Format a Value Directly
Output:
Performing Operations in F-Strings
Python expressions can be evaluated directly inside placeholders.
Example: Arithmetic Operation
Output:
Example: Calculation Using Variables
Output:
Conditional Logic Inside F-Strings
You can use conditional expressions (if...else) within placeholders.
Example: Conditional Output
Output:
Calling Functions in F-Strings
Both built-in and user-defined functions can be executed inside f-strings.
Example: Built-in Function
Output:
Example: User-Defined Function
Output:
Advanced Formatting Options
Example: Thousand Separator
Output:
Example: Percentage Format
Output:
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.
Example: Basic format() Usage
Output:
Example: Formatting with Decimals
Output:
Formatting Multiple Values
Example: Multiple Placeholders
Output:
Using Index Numbers
Index numbers ensure values appear in the correct position.
Example: Indexed Placeholders
Output:
Example: Reusing the Same Value
Output:
Named Placeholders
Named placeholders improve readability when working with many values.
