考虑到PEP-8处理长琴弦的最佳方法是什么?

fre*_*rik 5 python

结果字符串有一个换行符(我相信这个语法会破坏我的IDE中的函数折叠):

>>> def linebreak():
>>>     return """Hello this is a really long string which eventually
>>> needs to be breaked due to line length"""
>>> print(linebreak())
Hello this is a really long string which eventually
needs to be breaked
Run Code Online (Sandbox Code Playgroud)

这样更好,但这不仅包括换行符,还包括结果字符串中的多个空格:

>>> def whitespace():
>>>     some_string = """Hello this is a really long string which eventually
>>>                      needs to be breaked due to line length"""
>>> print(whitespace())
Hello this is a really long string which eventually
                     needs to be breaked
Run Code Online (Sandbox Code Playgroud)

正如SO Q/A中所建议的那样,您必须仔细格式化每一行(这非常繁琐),以确保您以空格结束或开始.如果您在最初创建字符串后碰巧编辑了字符串,那么您最终也可能会看到具有非常奇怪的行长度的文本行(想象10行长度非常不同的文本):

>>> def tedious():
>>>     return ('Hello this is a really long string which eventually '
>>>             'needs to be breaked due to line length')
>>> print(tedious())
Hello this is a really long string which eventually needs to be breaked due to line length
Run Code Online (Sandbox Code Playgroud)

关于如何使用PEP-8定义长字符串并且在我定义它们时没有明确地获得换行符或空格的共同共识是什么?

这是非常复杂但有点做我想要的,虽然它使得无法明确定义换行符:

>>> def hello():
>>>     return ' '.join("""Hello this is a really long string which
>>>                        eventually needs to be breaked due to line
>>>                        length""".split())
>>> print(hello())
>>> Hello this is a really long string which eventually needs to be breaked due to line length
Run Code Online (Sandbox Code Playgroud)

问题:有关改进这种最后复杂方法的任何建议吗?


更新

由于这个问题是[关闭]我只想补充一点,我觉得textwrap.dedent是最好的解决方案(对我来说)所描述的在这里.还有另一个问题(没有关闭)有许多其他的建议:Pythonic方法来创建一个长的多行字符串