Member-only story

9 Powerful and Creative Ways to Use F-Strings in Python

Python Coding
2 min readSep 11, 2024

--

1. Basic Variable Interpolation

You can insert variables directly into strings.

name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
My name is Alice and I am 30 years old.

2. Expression Evaluation

You can include expressions inside f-strings.

a = 10
b = 5
print(f"Sum of {a} and {b} is {a + b}.")
Sum of 10 and 5 is 15.

3. Formatting Numbers

F-strings make it easy to format numbers for better readability.

value = 1234.56789
print(f"Formatted value: {value:.2f}")
Formatted value: 1234.57

4. Working with Dictionaries

You can access dictionary keys within f-strings.

person = {'name': 'Bob', 'age': 28}
print(f"Person's name is {person['name']}and age is {person['age']}.")
Person's name is Boband age is 28.

--

--

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

Responses (3)