Python风格 - 字符串的连续性? [英] Python style - line continuation with strings?

查看:157
本文介绍了Python风格 - 字符串的连续性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试服从python风格规则,我已经设置我的编辑器最多79 cols。

In trying to obey the python style rules, I've set my editors to a max of 79 cols.

在PEP,它建议使用python的隐含的延续括号,括号和大括号。

In the PEP, it recommends using python's implied continuation within brackets, parentheses and braces. However, when dealing with strings when I hit the col limit, it gets a little weird.

例如,尝试使用多行

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

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

But, when the statement is indented a few blocks in, this looks weird:

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there \
wonderful stackoverflow people!"

如果您尝试缩进第二行:

If you try and indent the second line:

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there \
            wonderful stackoverflow people!"

您的字符串最后为:

"Why, hello there                wonderful stackoverflow people!"

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

The only way I've found to get around this is:

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there" \
            "wonderful stackoverflow people!"

我喜欢更好,但也有些不安的眼睛,因为它看起来像字符串只是坐在无处的中间。这将产生正确的:

Which I like better, but is also somewhat uneasy on the eyes, as it looks like there is a string just sitting in the middle of nowhere. This will produce the proper:

"Why, hello there wonderful stackoverflow people!"

所以,我的问题是 - 一些人的建议如何做到这一点,

So, my question is - what are some people's recommendations on how to do this and is there something I'm missing in the style guide that does show how I should be doing this?

感谢。

推荐答案

由于相邻字符串文字会自动合并为单个字符串,你可以使用PEP 8建议的括号内的隐式行继续:

Since adjacent string literals are automatically joint into a single string, you can just use the implied line continuation inside parentheses as recommended by PEP 8:

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

这篇关于Python风格 - 字符串的连续性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆