为了遵守python样式规则,我将我的编辑器设置为最多79个cols。
在PEP中,它建议在方括号、圆括号和大括号中使用python的隐含延续。然而,当我遇到列限制时,当我处理字符串时,它变得有点奇怪。
例如,尝试使用多行
mystr = """Why, hello there
wonderful stackoverflow people!"""
将会返回
"Why, hello there\nwonderful stackoverflow people!"
这是可行的:
mystr = "Why, hello there \
wonderful stackoverflow people!"
由于它返回以下内容:
"Why, hello there wonderful stackoverflow people!"
但是,当语句缩进几个代码块时,这看起来很奇怪:
do stuff:
and more stuff:
and even some more stuff:
mystr = "Why, hello there \
wonderful stackoverflow people!"
如果您尝试缩进第二行:
do stuff:
and more stuff:
and even some more stuff:
mystr = "Why, hello there \
wonderful stackoverflow people!"
字符串的结尾为:
"Why, hello there wonderful stackoverflow people!"
我发现解决这个问题的唯一方法是:
do stuff:
and more stuff:
and even some more stuff:
mystr = "Why, hello there" \
"wonderful stackoverflow people!"
我更喜欢它,但在眼睛上也有些不舒服,因为它看起来就像是一根绳子就坐在一个不知名的地方。这将产生适当的:
"Why, hello there wonderful stackoverflow people!"
那么,我的问题是-一些人对如何做到这一点有什么建议,在风格指南中是否有我遗漏了什么,这说明了我应该如何做到这一点?
谢谢。
发布于 2011-03-26 04:16:21
从adjacent string literals are automatically joint into a single string开始,你可以像PEP8推荐的那样在括号中使用隐含的行续行:
print("Why, hello there wonderful "
"stackoverflow people!")
发布于 2015-09-16 08:09:30
只需指出是使用圆括号调用了自动连接。如果您恰好已经在语句中使用了它们,这是很好的。否则,我只会使用'\‘,而不是插入圆括号(这是大多数IDE自动为您做的)。缩进应使字符串连续对齐,以使其符合PEP8。例如:
my_string = "The quick brown dog " \
"jumped over the lazy fox"
发布于 2016-10-04 11:42:18
另一种可能是使用textwrap模块。这也避免了问题中提到的"string只是坐在一个不知名的地方“的问题。
import textwrap
mystr = """\
Why, hello there
wonderful stackoverfow people"""
print (textwrap.fill(textwrap.dedent(mystr)))
https://stackoverflow.com/questions/5437619
复制相似问题