得到的字符串有一个linebreak(我相信这个语法破坏了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
这是更好的,但这不仅包括换行符,还包括结果字符串中的许多空格:
^{pr2}$正如本文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
目前没有回答
相关问题 更多 >
编程相关推荐