所以,这是我的代码片段:
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))
我添加了"\"来分解字符串,但是当我打印它时,出现了这个巨大的空白。
您将如何在不扭曲代码的情况下拆分代码?
谢谢!
您可以在整个表达式两边加上括号:
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()
会为您执行此操作。
不要在中间换行,而是使用由行继续符分隔的两个字符串,但最好使用括号
return ("a Parallelogram with side lengths {} and {}, and interior angle "
"{}".format(1, 2, 3))
以下内容也适用于 Python 3+ 中较新的字符串格式化技术:
print(
f"a Parallelogram with side lengths {self.base} and {self.side}, "
f"and interior angle {self.theta}"
)