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

时间:2016-10-28 15:00:30

标签: 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

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

>>> 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

正如本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

关于如何在考虑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

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

更新

由于这个问题已经[关闭],我想补充一点,我认为textwrap.dedent是最好的解决方案(对我而言),如here所述。还有另一个问题(没有结束)有许多其他建议:Pythonic way to create a long multi-line string

0 个答案:

没有答案