Python's Not (Just) For Unicorns

Formatting output with f strings

I have to admit something: Python invented motorcycles a while ago, but I’ve only been teaching you to ride a bike. The guilt has finally gotten to me, so I’m coming clean and sharing a secret.

You know how we’ve been using print to print things out? And putting a comma between the sections?

name = 'Laksmi'
print('Hello, my name is', name)

It’s definitely not the best way to do it - it’s old school, it’s inflexible, and just… people do it, it works, but it’s just not modern.

As of Python 3.6, there is a cool fun new thing called f strings! It’s the one new feature we might actually use. Instead of using the comma weirdness, we can do this:

name = 'Laksmi'
print(f'Hello, my name is {name}')

Two things to notice:

The string starts with f', not just ' (f" works too)

The variable is inside of curly braces {}

It works just like a fill-in-the-blank. The f before the string says “hey, we’re going to put some variables in here!” and the {name} says “put the name variable in here!” and then everyone is happy and we didn’t have to use a hundred commands.

Python’s f-strings also work with numbers, and even math!

minutes = 2.5
print(f'You will have to wait {minutes * 60} seconds')

Instead of calculating a new seconds variable, we just did the math inside of the curly braces! And if you think that’s amazing, maybe you should just skip the next section, because your life is about to change forever.

When you’re using your variable, you can also add weird little modifiers to tell Python how you want the variable displayed. It’s mostly used with numbres - you can add commas to big numbers, round long decimal numbers, left- or right-align, or a hundred other things!

As long as we always put an f before you start the string, we’ll always be able to use these nice fill-in-the-blanks.

Okay. Whew. Our minds have been blown out into space, but it might be worth trying this out on our own real quick. Remember when we printed out the populations of the cities last chapter? Let’s try to reproduce it agian, but with f strings.

Let’s print out the name of the city and the population, but we’ll use the long number and format it with commas. For example, it should start with “Santiago has a population of 7,200,000”.