0
0
Pythonprogramming~5 mins

String formatting using f-strings in Python

Choose your learning style9 modes available
Introduction

F-strings help you put values inside text easily and clearly. They make your messages or results look nice and readable.

When you want to show a message with numbers or names mixed in.
When you need to create a sentence that includes changing information.
When you want to print results from calculations inside a sentence.
When you want to build a file name or path using variables.
When you want to format dates or prices neatly in text.
Syntax
Python
f"text {variable} more text {expression}"
Start the string with the letter f before the quotes.
Put variables or expressions inside curly braces {} to include their values.
Examples
Insert a variable name inside the text.
Python
name = "Anna"
print(f"Hello, {name}!")
Show a number variable inside a sentence.
Python
age = 25
print(f"You are {age} years old.")
Calculate inside the braces and show the result.
Python
x = 5
y = 3
print(f"Sum is {x + y}.")
Format a number to 2 decimal places.
Python
price = 9.99
print(f"Price: ${price:.2f}")
Sample Program

This program shows how to use f-strings to print variables and expressions in sentences.

Python
name = "Sam"
age = 30
height = 1.75

print(f"Name: {name}")
print(f"Age: {age} years")
print(f"Height: {height} meters")
print(f"Next year, {name} will be {age + 1} years old.")
OutputSuccess
Important Notes

You can put any expression inside the braces, like math or function calls.

F-strings work only in Python 3.6 and later versions.

Use :.2f inside braces to format floats with 2 decimals.

Summary

F-strings make it easy to mix text and values in one string.

Use curly braces {} to insert variables or expressions.

They help create clear and readable output messages.