Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

String Formatting With f-Strings

Learn about what Python’s formatted string literals (f-strings) are and when to use them. You’ll see that f-strings allow you to use embedded Python expressions inside string constants:

>>>
>>> f'Hello, {name}!'
'Hello, Bob!'

This lesson will also show you how to use f-strings for:

  • Simple string formatting and
  • Inline arithmetic

Comments & Discussion

Karl on May 4, 2019

Hey, as a not native english speaker, it is easy to me to understand your speech. Thanks! :-)

Abby Jones on June 27, 2019

This doesn’t work for me for some reason.

f'Five plus ten is {a + b} and not {2 * (a + b)}.'

Dan Bader RP Team on June 27, 2019

@Abby: What’s the error message you’re getting? The following should work, as long as you’re on Python 3.6 or above:

>>> a = 5
>>> b = 10
>>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'
'Five plus ten is 15 and not 30.'

This formatting feature called f-strings is only available in Python versions 3.6 and up, so if you’re on a different version it won’t work.

Abby Jones on June 28, 2019

I’m using 7, but I was including .format erroneously.

Abby Jones on June 28, 2019

3.7, I mean.

Abby Jones on June 28, 2019

Okay hold up, I just tried it again and it doesn’t work in bpython at all. Syntax error

>>> a=5
>>> b=10
>>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'
  File "<input>", line 1
    f'Five plus ten is {a + b} and not {2 * (a + b)}.'
                                                     ^
SyntaxError: invalid syntax

Abby Jones on June 28, 2019

Okay, just verified that bypthon doesn’t allow this, but python prompt does.

Dan Bader RP Team on June 28, 2019

@Abby: You can install bpython on top of different versions of your local Python install. If bpython is installed on top of Python 3.6 or above, it will work:

$ bpython
bpython version 0.18 on top of Python 3.7.3 /Users/dbader/.pyenv/versions/3.7.3/bin/python3.7
>>> a=5
>>> b=10
>>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'
'Five plus ten is 15 and not 30.'

Abby Jones on June 28, 2019

Oh jeez, it is on top of 2.7 lol. hangs head in shame

Become a Member to join the conversation.