Python 风格 - 用字符串续行?

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

在 PEP 中,它建议在括号、圆括号和大括号内使用 python 的隐含延续。但是,当我达到 col 限制时处理字符串时,它会变得有点奇怪。

例如,尝试使用多行

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

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

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

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

谢谢。

最佳答案

自从 adjacent string literals are automatically joint into a single string ,您可以按照 PEP 8 的建议在括号内使用隐含的续行:

print("Why, hello there wonderful "
      "stackoverflow people!")

https://stackoverflow.com/questions/5437619/

相关文章:

linux - 在 grep 中转义双引号

linux - SVN中结帐和导出的区别

python - 两个长度不等的列表之间的排列

python - Python 2和3之间numpy数组的pickle不兼容

python - 如何在 Python 中设计一个类?

linux - 连接到主机 localhost 端口 22 : Connection refused

python - 为什么不自动调用父类(super class) __init__ 方法?

python - Django admin 中同一模型的多个 ModelAdmins/ View

linux - linux命令末尾的 "&"是什么意思?

linux - 可能有多少个套接字连接?