user300
user300

Reputation: 465

how to fix this invalid syntax error

I get an invalid syntax error for this code:

def __str__(self):
        s= 'Patron("'+self.name+'","'+self.patron_id+'","['+ \
        for book in self.borroweds:
            s+=str(book) + ', '
        if len(self.borroweds) != 0:
            s= s[:-2]
        s+='])' 
        return s



    for book in self.borroweds:
      ^
SyntaxError: invalid syntax
>>> 

I know it's because I have a "\" but I put that so i can continue writing my code

Upvotes: 1

Views: 748

Answers (2)

Hugh Bothwell
Hugh Bothwell

Reputation: 56644

def __str__(self):
    books = ', '.join(self.borroweds)
    return 'Patron("{name}", "{id}", [{books}])'.format(name=self.name, id=self.patron_id, books=books)

Upvotes: 0

Ray Toal
Ray Toal

Reputation: 88378

The backslash means the line is not over, so your code is exactly equivalent to

s = 'Patron("'+self.name+'","'+self.patron_id+'","['+ for book in self.borroweds:

which gives you a syntax error at the for keyword, since Python is looking for an expression that evaluates to a string there. You should take out the + and the backslash. It appears you would be happy to simply initialize s as follows:

s = 'Patron("'+self.name+'","'+self.patron_id+'","['

and then let subsequent line of your code add to the string s.

For details on the line structure of Python programs, including what is meant by explicit and implicit line joining, and how to think about the backslash character, see this section of the Python reference manual.

Upvotes: 2

Related Questions