繁体   English   中英

在Python中打破没有空格的长字符串

[英]Breaking long string without the spaces in Python

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

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}"
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM