Search code examples
pythonpython-3.xsyntax-errorf-string

Python SyntaxError on fstring in the __repr__ method of the class


My code:

class Book:
    all = []
    def __init__(self, ISBN, title, subject, publisher, language, number_of_pages):
        self.__ISBN = ISBN
        self.__title = title
        self.__subject = subject
        self.__publisher = publisher
        self.__language = language
        self.__number_of_pages = number_of_pages
        self.__authors = []

        Book.all.append(self)

    def __repr__(self):
        return f"Title {self.__title} Subject {self.__subject}"

b = Book(23498723,"this","fiction","penguin","en",196)

Error:

    return f"Title {self.__title} Subject {self.__subject}"
                                                          ^
SyntaxError: invalid syntax

Could anyone explain why this is an error?


Solution

  • Your Python vesion does not support "f-strings".

    "The release of Python version 3.6 introduced formatted string literals, simply called f-strings."

    You can upgrade to python version 3.6 or the latest version. Download and use python version 3.6 or later from this link: https://www.python.org/downloads/release/python-3615/