String Formatting with F-StringsΒΆ

Having to concatenate strings with all those open and close quotes and plus signs and spaces to forget can be a pain. But there’s a better way. F-strings!

Here’s how we’ve been doing things:

>>> conference = "PyCon"
>>> year = "2017"
>>> conference + " " + year + " is really great!"
'PyCon 2017 is really great!'

With f-strings we can simplify quite a bit.

>>> conference = "PyCon"
>>> year = "2017"
>>> f'{conference} {year} is really great!'
'PyCon 2017 is really great!'

So we create a variable for the conference and a variable for the year, then we can reference them within the string with {variable} syntax. The only thing we need to do to make this work is to include f at the beginning of string. No need to concatenate a bunch of spaces, and it’s much easier to read. Neat!