-1

I was taking the fast.ai course and came across this snippet of code (in Python 3):

PATH = "data/dogscats/"
os.listdir(f'{PATH}valid')

This returns the list of the files in the directory data/dogscats/valid, like I expected. However, I don't understand what purpose the "f" in front of '{PATH}valid' serves. When removed, the code throws a "FileNotFound" error. Why is the "f" there? It's not even part of the string? I know this might be an elementary question, but it's something I'd love to understand.

Thank you in advance!

Shawn Lee
  • 143
  • 1
  • 9

2 Answers2

2

f-string is really an expression evaluated at runtime, not a constant value. In Python, an f-string is a literal string, prefixed with f, which contains expressions inside braces. The expressions are replaced with their values.

So, f'{PATH}valid' gets evaluated to data/dogscats/valid.

DEEPAK SURANA
  • 431
  • 3
  • 14
1

It's new in Python 3.6, introduced in PEP 498, and it's called an f-string for formatted string literal. There are many ways to do similar things in Python; the oldest is the standard string interpolation using %, then the string .format() method, and now f-strings, for e.g.:

>>> '%svalid' % 'data/dogscats/'
'data/dogscats/valid'
>>> '{PATH}valid'.format(PATH='data/dogscats/')
'data/dogscats/valid'
>>> PATH = 'data/dogscats/'
>>> f'{PATH}valid'
'data/dogscats/valid'

It can be more than just a substitution of values however, as you can actually evaluate expressions as well:

>>> x = 5
>>> f'The value of {x}^2 is {x**2}'
'The value of 5^2 is 25'

From the docs on f-strings:

A formatted string literal or f-string is a string literal that is prefixed with 'f' or 'F'. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.

alkasm
  • 22,094
  • 5
  • 78
  • 94