Python F-Strings Tutorial – Complete Guide

Welcome to a comprehensive guide on one of Python’s most valuable and useful features: f-strings. As programmers, we frequently deal with strings, and Python provides several ways to format strings. Among them, f-strings or formatted string literals offer a succinct and readable way to embed expressions inside string literals.

What are Python F-strings?

F-strings, introduced in Python 3.6, are a modern, advanced way to format strings in Python. Instead of using complex and sometimes unclear formatting options, f-strings allow you to directly embed variables and expressions within the string itself, using curly brackets {}.

Why Use Python F-strings?

Why should you learn f-strings? Here’s why:

  • F-strings are easy to read and write. They help keep your code clean and concise.
  • They perform better than other formatting methods. F-strings are faster because they are evaluated at runtime.
  • F-strings can incorporate any Python expression, offering greater flexibility.

Hence, understanding f-strings is crucial for both beginners and experienced coders looking to streamline their Python coding process.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Python F-strings Basics

Let’s delve into the basics of Python f-strings with some examples.

Simple String Interpolation

The most basic use of f-strings is to directly interpolate variables into a string. Let’s see how:

name = "Zenva"
print(f"We are {name}")

This simple script will output ‘We are Zenva’. The variable ‘name’ is directly embedded in the string.

Using F-strings with expressions

But f-strings are not limited to variables only; we can include any valid Python expression. Check this out:

a = 10
b = 20
print(f"The sum of {a} and {b} is {a+b}")

That will output ‘The sum of 10 and 20 is 30’. We’ve embedded an arithmetic operation inside the f-string.

Advanced uses of Python F-strings

Continuing with our tutorial, let’s explore some more advanced uses of f-strings.

F-strings with dictionary keys

F-strings can directly read and format dictionary keys:

param = {'course':'Python', 'platform':'Zenva'}
print(f"Learn {param['course']} at {param['platform']}")

The above script will output ‘Learn Python at Zenva. Our f-string has directly read the dictionary keys.

Aligning text with F-strings

F-strings can also align text using embedded options. Take a look:

print(f"{'Zenva':>10}")

Here ‘Zenva’ will be right-aligned within an allocated space of 10 characters.

Formatting numbers with F-strings

Last but not least, f-strings can also format numbers:

num = 12.3456789
print(f"The number {num:.2f} rounded to 2 decimal places.")

By using the :.2f syntax inside the f-string, we are rounding ‘num’ to two decimal places in the output.

Further Uses of Python F-strings

Now that we’ve covered the basics and some intermediate usage, let’s explore more uses of Python f-strings.

Dynamic Expressions in F-strings

Because f-strings are interpreted at runtime, we can have dynamic expressions inside them:

table = 'Topics'
print(f"{'List of '+ table}")

We’ve used a string operation for the dynamic expression here, and the output will be ‘List of Topics’.

Using Functions within F-string

F-strings can directly call functions:

def greet(name):
    return "Hello " + name

print(f"{greet('Zenva')}")

The function ‘greet’ is called directly inside the f-string and the output will be ‘Hello Zenva’.

Nested F-strings

Yes, f-strings also allow nesting:

outer = 10
inner = 5
print(f"The outer total is {outer} and the inner total is {f'{inner}'}")

The output reads ‘The outer total is 10 and the inner total is 5’. We’ve nested an f-string inside another f-string.

F-strings with Classes and Objects

For those who use object-oriented Python, f-strings can even work with classes and objects:

class Zenva:
    course = 'Python'

print(f"We are offering {Zenva.course} courses")

This example prints ‘We are offering Python courses’ by accessing the ‘course’ attribute of the ‘Zenva’ class.

F-strings with Conditional Expressions

We can also use conditional (if-else) expressions in f-strings:

available = True
print(f"The

Python course

 is {'available' if available else 'not available'}")

The output is ‘The Python course is available’, using a conditional expression inside the f-string.

F-string with Loop Markers

Finally, let’s use f-string with loop markers:

for i in range(1,4):
    print(f"This is iteration {i}")

With each iteration, ‘i’ is printed in the string, which results in the output:

  • This is iteration 1
  • This is iteration 2
  • This is iteration 3

Where to Go Next with Python F-strings?

Congratulations on making it this far! But the journey doesn’t have to stop here. Even after mastering Python f-strings, there is a lot more to learn in Python coding. And the good news is: We at Zenva are here to accompany you throughout. A key avenue worth exploring is our comprehensive Python Mini-Degree.

Our Python Mini-Degree is a set of in-depth courses on Python programming. It spans from basics to algorithms, object-oriented programming to game development, and app development using popular Python libraries and frameworks. This extensive course is designed for people of all coding backgrounds. Whether you are a beginner or an experienced programmer, our flexible learning options and project-based assignments will meet your needs.

Apart from the Python Mini-Degree, we offer a wider range of Python courses covering various aspects of the language.

Conclusion

Python’s diverse and powerful features, such as f-strings, open up a world of possibilities for budding and experienced developers alike. Mastering these techniques is an integral part of developing efficient, readable, and professional-grade Python code.

We invite you to take that next step in your Python journey with us at Zenva. Whether it’s our all-encompassing Python Mini-Degree or one of our various individual Python courses, we support and challenge you in mastering Python for real-world applications. Together, let’s set the stage for your continued growth and success in the coding world!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.