7 f-strings Powerful Techniques That Will Blow Your Mind

What will you learn?

What is an f-string? Most know that but almost nobody knows the real power of f-strings. In this guide you will learn about it.

An f-string helps you get the string representations of variables.

name = 'Rune'
age = 32
print(f'Hi {name} you are {age} years old')

This will result in the output: ‘Hi Rune you are 32 years old’.

Most know that this is the structure of an f-string.

f'Some text {variable_a} and {variable_b}'

The structure.

  • It starts with f and has quotes afterwards: f’String content’ or f”String content”.
  • Then it will add the string representation of any variable within curly brackets f’String content {varriable_a}’

But there is more power to unleash.

#1 String representation of a class

This is actually a great way to know about Objects in general. If you implement a __str__(self) method it will be the string representation of object. And the best part is that f-string will get use that value as string representation of it.

class Item:
    def __init__(self, a):
        self.a = a
    def __str__(self):
        return str(self.a)
item = Item(12)
print(f'Item: {item}')

This will print ‘Item: 12‘.

#2 Date and time formatting

This is an awesome feature. You can format a date object as you wish.

from datetime import datetime
today = datetime.now()

print(f'Today is {today}')
# 'Today is 2022-04-13 13:13:47.090745'
print(f'Today is {today:%Y-%m-%d}')
# 'Today is 2022-04-13'
print(f'Time is {today:%H:%M%:%S}')
# 'Time is 13:13:47'

#3 Variable names

Another great one is you can actually include the variable names in the output. This is a great feature when you debug or add variables to the log.

x = 10
y = 20
print(f'{x = }, {y = }')
# 'x = 10, y = 20'
print(f'{x=}, {y=}')
# 'x=10, y=20'

#4 Class representation

Now this is not the same as the first one. An Object can have a class representation.

class Price:
    def __init__(self, item, price):
        self.item = item
        self.price = price
        
    def __str__(self):
        return f'{self.item} {self.price}'
    
    def __repr__(self):
        return f'Item {self.item}  costs {self.price} dollars'
p = Price('Car', 10)
print(f'{p}')
# 'Car 10'
print(f'{p!r}')
# 'Item Car  costs 10 dollars'

#5 Formatting specification

Now you can make a lot of formatting of the output.

Here are a few of them.

s = 'Hello, World!'
# Center output
print(f'{s:^40}')
# '             Hello, World!              '
# Left align
print(f'{s:<40}')
# 'Hello, World!                           '
# Right align
print(f'{s:>40}')
# '                           Hello, World!'
n = 9000000
print(f'{n:,}')
# '9,000,000'
print(f'{n:+015}')
# '+00000009000000'

#6 Nested f-strings

You can actually have f-strings within f-strings. This can have a few use-cases like these.

number = 254.3463
print(f"{f'${number:.2f}':>20s}")
# '             $254.35'
v = 3.1415
width = 10
precision = 3
print(f'output {v:{width}.{precision}}')
# 'output       3.14'

#7 Conditional formatting

There might be cases where this is useful.

v = 42.0
print(f'output {v:{"4.3" if v < 100 else "3.2"}}')
# 'output 42.0'
v = 142.0
f'output {v:{"4.3" if v < 100 else "3.2"}}'
# 'output 1.4e+02'

Want to learn more?

If this is something you like and you want to get started with Python, then check my 8 hours FREE video course with full explanations, projects on each levels, and guided solutions.

The course is structured with the following resources to improve your learning experience.

  • 17 video lessons teaching you everything you need to know to get started with Python.
  • 34 Jupyter Notebooks with lesson code and projects.
  • A FREE 70+ pages eBook with all the learnings from the lessons.

Leave a Reply

%d bloggers like this: