Python 3 SyntaxError: invalid syntax f strings

I was working on a old python project and I got error:

filename = f"{file}_{user.replace('/', '_')}.txt"                                                                 ^
SyntaxError: invalid syntax

After quick research I found that new features like f strings (introduced since python 3.6) are added to this project. So in order to solve problems like this one you need to update to python 3.6 and more. You can install latest Python on Ubuntu/Linux Mint by following steps in this article:

Python 3.7 Install and setup on Ubuntu and PyCharm

If you want to read more about this new feature you can find information here:

PEP 498 -- Literal String Interpolation

from this page we can read:

Python supports multiple ways to format text strings. These include %-formatting [1], str.format() [2], and string.Template [3]. Each of these methods have their advantages, but in addition have disadvantages that make them cumbersome to use in practice. This PEP proposed to add a new string formatting mechanism: Literal String Interpolation. In this PEP, such strings will be referred to as "f-strings", taken from the leading character used to denote such strings, and standing for "formatted strings".

Example

“f-strings” or formatted string literals are best described with example like this one:

lang = 'Python'
pos = 1
print(f'This language {lang} is at {pos} position in 2018.')

which is equivalent to:

lang = 'Python'
pos = 1
print('This language {} is at {} position in 2018.'.format(lang, pos))

The real use case and usage for f-strings would be embedding expressions into literals. So now You can add additional formatting of your values by using formatted string literals:

lang = 'Python 2.7'
anniversary = datetime.date(2020, 12, 31)
print(f'The support for {lang} ends in  {anniversary:%A, %B %d, %Y}')

val = None
print(f'Variable val has value: {val if val else False}')

val = "Error"
print(f'Variable val has value: {val if val else False}')

Advantages of f-strings

I can think of several advantages of the f-strigns like:

  • Simple Syntax
  • Big variety of expressions
  • f-strings has multiline support
  • good performance
  • working with single, double and triple quotes

Have in mind that escaping in f-strings can raise an error like:

SyntaxError: f-string expression part cannot include a backslash

as this example:

user = 1
print(f"C:\{\user}.")

Good news for PyCharm fans is that PyCharm fully support f-strings.

Related Article