17

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 the 80 chars for good styling in a line, 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 the "\" to break up the string, but then there is this huge blank gap when I print it.

How would you split the code without distorting it?

Thanks!

0

3 Answers 3

29

You can put parenthesis around the whole expression:

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

or you could 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 strings; Python automatically joins consecutive string literals into one:

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

I prefer parenthesis myself.

The str() calls are redundant; .format() does that for you by default.

Sign up to request clarification or add additional context in comments.

5 Comments

If you've got the parentheses in place, you can also put the line break before or after the . character. That's because it is a sort of operator (even though we don't often think of it that way), and operators allow flexible spacing on either side of them.
@Blckknght: I find any whitespace around . in attribute access to be too unreadable and ugly, myself.
I mostly agree, but when the format string would only have a small bit of itself wrapped on the second line (or when it's indentation causing most of the issue, rather than a long string), it can be useful. I almost always break before the dot, so it's func("formatstring"<newline_and_indentation_upto_the_(>.format(args)) which seems a bit better than the alternatives.
And amusingly, at least with my font, my comment indented itself exactly correctly to show what I meant...
@Blckknght: usually there are better alternatives. Such as defining the longer format string as a variable first.
1

Don't break the line in between instead use two strings separated by line continuation but best would be to use brackets

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

Comments

0

The following also works with the newer string formatting technique, in Python 3+:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.