gpt4 book ai didi

Python 风格 - 用字符串续行?

转载 作者:IT老高 更新时间:2023-10-28 12:26:38 25 4
gpt4 key购买 nike

为了遵守 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!")

关于Python 风格 - 用字符串续行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5437619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com