Member-only story

How to Use Python f-Strings?

Python Coding
2 min readAug 21, 2024

--

Basic Usage

Here’s a basic example of using f-strings:

name = "Alice"
age = 30

greeting = f"Hello, my name is {name} and I am {age} years old."
print(greeting)
Hello, my name is Alice and I am 30 years old.

Embedding Expressions

You can also embed expressions directly inside f-strings:

length = 5
width = 3

area = f"The area of the rectangle is {length * width} square units."
print(area)
The area of the rectangle is 15 square units.

Formatting Numbers

F-strings also allow you to format numbers:

pi = 3.141592653589793

formatted_pi = f"Pi rounded to two decimal places is {pi:.2f}."
print(formatted_pi)
Pi rounded to two decimal places is 3.14.

Using Functions Inside F-Strings

You can even call functions within an f-string:

def greet(name):
return f"Hello, {name}!"

message = f"{greet('Alice')}"
print(message)

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

No responses yet