PYTHON
Stop doing print(f”variable = {variable}”)
Python 3.6, all the way back in 2016, introduced a new string formatting method called f-strings, which stands for formatted string literal.
Today they’re pretty much ubiquitous for printing variables in Python.
F-strings are faster than the other string formatting methods and are easier to read and use.
Here are some tricks you may not have known existed.
Code for this article 👇
1. Debug mode
The first one is the debug feature with f-strings.
Instead of writing out “variable = “
, do {variable = }
instead.
This saves a lot of time and effort, as well as makes your code look cleaner.
Within f-strings debugging, you can also perform math operations as you see in the last line.
x = 10
y = 20
print(f"x = {x}, y = {y}")
print(f"{x = }, {y = }")
# math operations
print(f"{x * y = }")
x = 10, y = 20
x = 10, y = 20
x * y = 200
2. Number formatting
There are various formatting/conversions you can perform with strings.
The following are done below
- set decimal places
:.nf
where n is the number of decimal places - hex conversion
- binary conversion
- octal conversion
- scientific notation
- pad number with leading zeros
:0n
where n is the total number of characters
number = 420
# decimal places
print(f"number: {number:.2f}")
# hex conversion
print(f"hex: {number:#0x}")
# binary conversion
print(f"binary: {number:b}")
# octal conversion
print(f"octal: {number:o}")
# scientific notation
print(f"scientific: {number:e}")
# total number of characters
print(f"Number: {number:09}")
number: 420.00
hex: 0x1a4
binary: 110100100
octal: 644
scientific: 4.200000e+02
Number: 000000420
What about large numbers and percentages?
Let’s say you have a large number, as large as Apple’s market cap; you can use :,
where ,
is the separator
Or, if you want f string to print out a percentage value, you can use :.2%
telling Python to set 2 decimal places and add a percentage sign to the end of the string.
apple_marketcap = 2.626 * 10e12
print(f"{apple_marketcap = :,}") # comma separator
percentage = 10.394394
print(f"{percentage = :.2%}") # percentage
apple_marketcap = 26,260,000,000,000.0
percentage = 1039.44%
3. Date formatting
Now, what if you want to format your dates?
Let’s create a sample date time value.
Just like how you would format dates with pandas or in your application, you’d define the format you want in the f-string by doing :<date_format>
Below we format a UTC DateTime to:
- no microseconds
- date only
- time only
- time with AM/PM
- 24-hour format
import datetime
today = datetime.datetime.utcnow()
print(f"datetime : {today}\n")
print(f"date time: {today:%m/%d/%Y %H:%M:%S}")
print(f"date: {today:%m/%d/%Y}")
print(f"time: {today:%H:%M:%S.%f}")
print(f"time: {today:%H:%M:%S %p}")
print(f"time: {today:%H:%M}")
datetime : 2022-09-13 05:44:17.546036
date time: 09/13/2022 05:44:17
date: 09/13/2022
time: 05:44:17.546036
time: 05:44:17 AM
time: 05:44
You could also do a lot more with the formatting options.
Here’s how you can get the weekday from the date and the day of the year.
You could also do something fun like calculating how far we are into the year.
It’s 70%, time flies!
# Locale’s appropriate date and time representation
print(f"locale appropriate: {today:%c}")
# weekday
print(f"weekday: {today:%A}")
# day of the year
print(f"day of year: {today:%j}")
# how far are we into the year?
day_of_year = f"{today:%j}"
print(f"progress % year: {int(day_of_year)/365 * 100:.2f}%")
locale appropriate: Tue Sep 13 05:44:17 2022
weekday: Tuesday
day of year: 256
progress % year: 70.14%
You can find more formatting options at https://strftime.org/
4. Repr & str
If you write OOP in Python, you’d be familiar with the dunder methods __repr__
and __str__
The basic idea is:
__repr__
= developer friendly__str__
= user friendly
Below is an example of a dataclass Person
with name and age attributes.
For a dataclass, by default (without a str
method defined), printing the object will give you the output of repr
.
With a str
the method defined, you’d need to write !r
to tell Python to print out the repr
method instead.
from dataclasses import dataclass
@dataclass
class Person:
name : str
age : int
def __str__(self) -> str:
return f"{self.name} is {self.age} years old"
Elon = Person("Elon Musk", 51)
print(f"{Elon}") # str
print(f"{Elon!r}") # repr
Elon Musk is 51 years old
Person(name='Elon Musk', age=51)
5. Alignment
If you want your variables to be printed at a specific position, alignments are the way to go!
Notice in the first line number:n
. Here n stands for the width of space to print the variable number
starting from the string “is” (inclusive of the variable itself)
You also have options to do a left, center, or right alignment.
Here left:>20
means given a width of 20 characters print out the string “left text” starting from the left.
For center:^20
that means to leave whatever space is left on the left and right. Since the string “center text!” is 12 characters, the left and right would have four characters of white space.
If we put all three strings together with their formatting options, we would have a width of 60 to place the left, center, and right string variables.
number = 4
print(f"number is {number:4}") # width of 10
# numbers
for number in range(1, 5):
print(f"the number is {number:{number}}")
left = "left text"
center = "center text!"
right = "right text"
print(f"{left:>20}") # left align
print(f"{center:^20}") # center align
print(f"{right:<20}") # right align
print(f"{left : <20}{center : ^20}{right : >20}")
number is 4
the number is 1
the number is 2
the number is 3
the number is 4
left text
center text!
right text
left text center text! right text
6. Multi-line f-string
Last but not least, you can have multiple lines within an f-string.
Just use triple quotes '''
and then define anything you want within the f-string.
Here’s an example below.
company_name = "Tesla"
employee_count = 100000
mission = "To accelerate the world's transition to sustainable energy"
print(f"""
Company: {company_name}
# of employees: {employee_count:,}
Mission: {mission}
""")
Company: Tesla
# of employees: 100,000
Mission: To accelerate the world's transition to sustainable energy
Thanks for reading!
More about f-strings from the docs
Like this article? Here are three articles you may like:
Want to discuss the latest developments in Data Science and AI with other data scientists? Join our discord server!
Follow Bitgrit’s socials 📱 to stay updated on workshops and upcoming competitions!