python - 如何编写符合 PEP8 的超长字符串并防止 E501

由于 PEP8 建议将您的 python 程序的列规则保持在 80 列以下,我如何才能遵守长字符串的规定,即

s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."

我将如何将其扩展到以下行,即

s = "this is my really, really, really, really, really, really" + 
    "really long string that I'd like to shorten."

最佳答案

由于相邻的字符串常量是自动连接的,你可以这样编码:

s = ("this is my really, really, really, really, really, really, "  
     "really long string that I'd like to shorten.")

注意没有加号,我在您的示例格式后面添加了额外的逗号和空格。

就我个人而言,我不喜欢反斜杠,我记得在某处读到它实际上已被弃用,而是支持这种更明确的形式。记住“显式优于隐式。”

我认为反斜杠不太清晰,也不太有用,因为它实际上是在转义换行符。如果有必要的话,不可能在它后面加上行尾注释。可以使用连接的字符串常量来做到这一点:

s = ("this is my really, really, really, really, really, really, " # comments ok
     "really long string that I'd like to shorten.")

我使用 Google 搜索“python line length”,它返回 PEP8 链接作为第一个结果,但也链接到另一个关于此主题的好 StackOverflow 帖子:“Why should Python PEP-8 specify a maximum line length of 79 characters?”

另一个很好的搜索短语是“python line continuation”。

https://stackoverflow.com/questions/1874592/

相关文章:

linux - 以不同用户身份运行 Linux 服务的最佳实践

linux - 将主机端口转发到 docker 容器

python - 如何删除numpy数组中的特定元素

linux - 如何从另一个文件A中删除文件B上出现的行?

linux - 如何提取 rpm 的内容?

python - 在 Pandas 中将 float 转换为整数?

python - 如何使用 Pyplot 在所有子图之上设置一个主标题?

linux - 比较 bash 中的整数,需要一元运算符

python - 在外部范围中定义的阴影名称有什么问题?

linux - 了解 Linux/proc/pid/maps 或/proc/self/maps