Back to course

String Formatting 2: F-Strings (Formatted String Literals)

Python Programming: The 0 to Hero Bootcamp

F-Strings: The Modern Way

F-strings (Formatted String Literals), introduced in Python 3.6, are the recommended, easiest, and fastest way to format strings.

To create an f-string, simply prefix the string literal with the letter f or F.

Basic F-string Usage

Variables are embedded directly inside the curly braces {} within the string.

python item = 'Laptop' price = 1250.99 quantity = 2

message = f"You bought {quantity} units of {item} for a total of ${price * quantity:.2f}." print(message)

Output: You bought 2 units of Laptop for a total of $2501.98.

Embedding Expressions

You can run Python expressions directly inside the braces, including arithmetic, function calls, or even method calls.

python import datetime current_time = datetime.datetime.now()

text = 'hello world'

Expression inside brackets

formatted = f"The current year is {current_time.year}. The title case is {text.title()}." print(formatted)

Output: The current year is 2024. The title case is Hello World.

Alignment and Padding

F-strings allow precise control over formatting, useful for reports or tables.

CharacterMeaning
<Left align
>Right align
^Center align

python value = 150 print(f"Centered: |{value:^10}|") # Center in 10 spaces print(f"Right: |{value:>10}|") # Right align in 10 spaces

Output:

Centered: | 150 |

Right: | 150|