Using f-strings for String Formatting in Python
Introduction
String formatting is an essential skill in Python, making it easier to create and manage dynamic text. Python introduced f-strings (formatted string literals) in version 3.6, offering a more readable and concise way to format strings compared to older methods like %
and .format()
.
What are f-strings?
f-strings, denoted by an f
or F
prefix before the opening quote, allow embedding expressions inside string literals using curly braces {}
. They enhance code readability and maintainability by providing a clear and straightforward syntax.
Output:
Expressions in f-strings
f-strings can include any valid Python expression inside the curly braces:
Output:
Using f-strings with Dictionaries and Lists
f-strings can access elements of dictionaries and lists directly:
Output:
Multi-line f-strings
f-strings also support multi-line formatting:
Output:
Subscribe to my newsletter
Read articles from Shrey Dikshant directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Shrey Dikshant
Shrey Dikshant
Aspiring data scientist with a strong foundation in adaptive quality techniques. Gained valuable experience through internships at YT Views, focusing on operation handling. Proficient in Python and passionate about data visualization, aiming to turn complex data into actionable insights.