DEV Community

Cover image for f-Strings in Python
tcs224
tcs224

Posted on

f-Strings in Python

If you programmed in Python before, you probably know how to use strings. You also know that formatting can be quite cumbersome, using %-formatting makes it look not elegant:

$ python3
Python 3.7.3 (default, Apr  3 2019, 05:39:12) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> name = "Veronica"
>>> "Hello %s" % name
'Hello Veronica'

To use multiple variables, it already starts looking cryptic

>>> name = "Veronica"
>>> age = 25
>>> "I am %s and I am %i years old." % (name,age)
'I am Veronica and I am 25 years old.'
>>>

%-formatting isn't that great, it becomes unreadable with a lot of parameters. Consider this example with manay parameters:

>>> name = "Veronica"
>>> age = 25
>>> lastname = "Sofia"
>>> job = "Teacher"
>>> relation = "Single"
>>> "Im %s %s, Im %i years old and a %s. Im %s" % (name,lastname, age,job,relation)
'Im Veronica Sofia, Im 25 years old and a Teacher. Im Single'
>>>

f-Strings

In Python >= 3.6 there's f-Strings. They make life much easier. To define one, you need to put an f in the beginning.

Take a look at these examples using f-Strings:
For two variables:

>>> f"Hello {name}. I am {age}"
'Hello Veronica. I am 25'

With multiple variables:

>>> f"Im {name} {lastname}, Im {age} years old and a {job}. Im {relation}"
'Im Veronica Sofia, Im 25 years old and a Teacher. Im Single'
>>> 

Related links:

Top comments (0)