Breaking a long string without spaces in Python

So here is a snippet of my code:

return "a Parallelogram with side lengths {} and {}, and interior angle 
{}".format(str(self.base), str(self.side), str(self.theta)) 

It goes beyond 80 characters for a good line style, so I did this:

return "a Parallelogram with side lengths {} and {}, and interior angle\
{}".format(str(self.base), str(self.side), str(self.theta)) 

I added "\" to break the line, but then I see this huge space when I type it.

How would you split the code without distorting it?

Thanks!

+4
source share
2 answers

You can put parentheses around the whole expression:

return ("a Parallelogram with side lengths {} and {}, and interior "
        "angle {}".format(self.base, self.side, self.theta))

or you can still use \to continue the expression, just use separate string literals:

return "a Parallelogram with side lengths {} and {}, and interior " \
       "angle {}".format(self.base, self.side, self.theta)

Note that there is no need to put +between the lines; Python automatically concatenates consecutive string literals into one:

>>> "one string " "and another"
'one string and another'

.

str() ; .format() .

+13

, , ,

return ("a Parallelogram with side lengths {} and {}, and interior angle "
"{}".format(1, 2, 3))
+1

All Articles