14

所以,这是我的代码片段:

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

它超出了 80 个字符的良好样式,所以我这样做了:

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

我添加了“\”来分解字符串,但是当我打印它时会出现这个巨大的空白。

你将如何在不扭曲代码的情况下拆分代码?

谢谢!

4

3 回答 3

23

您可以在整个表达式周围加上括号:

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

或者您仍然可以使用\继续表达式,只需使用单独的字符串文字:

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

+请注意,字符串之间不需要放置;Python 自动将连续的字符串文字合并为一个:

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

我自己更喜欢括号。

str()调用是多余的;.format()默认情况下会为您执行此操作。

于 2013-10-04T23:30:48.670 回答
1

不要在中间换行,而是使用由行继续分隔的两个字符串,但最好是使用括号

return ("a Parallelogram with side lengths {} and {}, and interior angle "
"{}".format(1, 2, 3))
于 2013-10-04T23:31:08.117 回答
0

以下内容也适用于 Python 3+ 中较新的字符串格式化技术

print(
  f"a Parallelogram with side lengths {self.base} and {self.side}, "
  f"and interior angle {self.theta}"
)
于 2021-11-10T05:16:14.427 回答