首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python风格--字符串的行续写?

Python风格--字符串的行续写?
EN

Stack Overflow用户
提问于 2011-03-26 04:12:37
回答 5查看 131.1K关注 0票数 166

为了遵守python样式规则,我将我的编辑器设置为最多79个cols。

在PEP中,它建议在方括号、圆括号和大括号中使用python的隐含延续。然而,当我遇到列限制时,当我处理字符串时,它变得有点奇怪。

例如,尝试使用多行

代码语言:javascript
复制
mystr = """Why, hello there
wonderful stackoverflow people!"""

将会返回

代码语言:javascript
复制
"Why, hello there\nwonderful stackoverflow people!"

这是可行的:

代码语言:javascript
复制
mystr = "Why, hello there \
wonderful stackoverflow people!"

由于它返回以下内容:

代码语言:javascript
复制
"Why, hello there wonderful stackoverflow people!"

但是,当语句缩进几个代码块时,这看起来很奇怪:

代码语言:javascript
复制
do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there \
wonderful stackoverflow people!"

如果您尝试缩进第二行:

代码语言:javascript
复制
do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there \
            wonderful stackoverflow people!"

字符串的结尾为:

代码语言:javascript
复制
"Why, hello there                wonderful stackoverflow people!"

我发现解决这个问题的唯一方法是:

代码语言:javascript
复制
do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there" \
            "wonderful stackoverflow people!"

我更喜欢它,但在眼睛上也有些不舒服,因为它看起来就像是一根绳子就坐在一个不知名的地方。这将产生适当的:

代码语言:javascript
复制
"Why, hello there wonderful stackoverflow people!"

那么,我的问题是-一些人对如何做到这一点有什么建议,在风格指南中是否有我遗漏了什么,这说明了我应该如何做到这一点?

谢谢。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2011-03-26 04:16:21

adjacent string literals are automatically joint into a single string开始,你可以像PEP8推荐的那样在括号中使用隐含的行续行:

代码语言:javascript
复制
print("Why, hello there wonderful "
      "stackoverflow people!")
票数 257
EN

Stack Overflow用户

发布于 2015-09-16 08:09:30

只需指出是使用圆括号调用了自动连接。如果您恰好已经在语句中使用了它们,这是很好的。否则,我只会使用'\‘,而不是插入圆括号(这是大多数IDE自动为您做的)。缩进应使字符串连续对齐,以使其符合PEP8。例如:

代码语言:javascript
复制
my_string = "The quick brown dog " \
            "jumped over the lazy fox"
票数 51
EN

Stack Overflow用户

发布于 2016-10-04 11:42:18

另一种可能是使用textwrap模块。这也避免了问题中提到的"string只是坐在一个不知名的地方“的问题。

代码语言:javascript
复制
import textwrap
mystr = """\
        Why, hello there
        wonderful stackoverfow people"""
print (textwrap.fill(textwrap.dedent(mystr)))
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5437619

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档