Python

Python F-strings Tricks You Should Know

Stop doing print(f”variable = {variable}”)

Benedict Neo
bitgrit Data Science Publication

--

Photo by Jörg Angeli on Unsplash

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.

Use Pandas? Here are 40 useful pandas commands you need to know.

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.

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

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.

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

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!

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.

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.

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.

Thanks for reading!

More about f-strings from the docs

Liked this article? Here are three articles you may like:

Be sure to follow the bitgrit Data Science Publication to keep updated!

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!

Like my writing? Join Medium with my referral link. You’ll be supporting me directly 🤗

--

--