DEV Community

Cover image for f-Strings in Python
tcs224
tcs224

Posted on

4 1

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:

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →