用 Python 换行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3346230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:34:38  来源:igfitidea点击:

Wrap long lines in Python

pythonstring

提问by user225312

How do I wrap long lines in Python without sacrificing indentation?

如何在不牺牲缩进的情况下在 Python 中包装长行?

For example:

例如:

def fun():
    print '{0} Here is a really long sentence with {1}'.format(3, 5)

Suppose this goes over the 79 character recommended limit. The way I read it, here is how to indent it:

假设这超过了 79 个字符的推荐限制。我阅读它的方式,这里是如何缩进它:

def fun():
    print '{0} Here is a really long \
sentence with {1}'.format(3, 5)

However, with this approach, the indentation of the continued line matches the indentation of the fun(). This looks kinda ugly. If someone was to go through my code, it would look bad to have uneven indentation because of this printstatement.

但是,使用这种方法,连续行的缩进与fun(). 这看起来有点丑。如果有人要查看我的代码,由于此print语句而出现不均匀的缩进看起来很糟糕。

How do I indent lines like this effectively without sacrificing code readability?

如何在不牺牲代码可读性的情况下有效地缩进这样的行?

采纳答案by pv2b

def fun():
    print(('{0} Here is a really long '
           'sentence with {1}').format(3, 5))

Adjacent string literals are concatenated at compile time, just as in C. http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenationis a good place to start for more info.

相邻的字符串文字在编译时连接起来,就像在 C 中一样。http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation是了解更多信息的好地方。

回答by Mark Byers

I'd probably split the long statement up into multiple shorter statements so that the program logic is separated from the definition of the long string:

我可能会将长语句拆分为多个较短的语句,以便将程序逻辑与长字符串的定义分开:

>>> def fun():
...     format_string = '{0} Here is a really long ' \
...                     'sentence with {1}'
...     print format_string.format(3, 5)

If the string is only just too long and you choose a short variable name then by doing this you might even avoid having to split the string:

如果字符串太长而您选择了一个简短的变量名称,那么通过这样做您甚至可以避免必须拆分字符串:

>>> def fun():
...     s = '{0} Here is a really long sentence with {1}'
...     print s.format(3, 5)

回答by Chris B.

You can use the fact that Python concatenates string literals which appear adjacent to each other:

您可以使用 Python 连接彼此相邻的字符串文字这一事实:

>>> def fun():
...     print '{0} Here is a really long ' \
...           'sentence with {1}'.format(3, 5)

回答by SilentGhost

You could use the following code where indentation doesn't matter:

您可以在缩进无关紧要的情况下使用以下代码:

>>> def fun():
        return ('{0} Here is a really long'
        ' sentence with {1}').format(3, 5)

You just need to enclose string in the parentheses.

您只需要将字符串括在括号中。

回答by Ioannis Filippidis

There are two approaches which are not mentioned above, but both of which solve the problem in a way which complies with PEP 8andallow you to make better use of your space. They are:

上面没有提到两种方法,但它们都以符合PEP 8的方式解决问题,允许您更好地利用您的空间。他们是:

msg = (
    'This message is so long, that it requires '
    'more than {x} lines.{sep}'
    'and you may want to add more.').format(
        x=x, sep=2*'\n')
print(msg)

Notice how the parentheses are used to allow us not to add plus signs between pure strings, and spread the result over multiple lines without the need for explicit line continuation '\' (ugly and cluttered). The advantages are same with what is described below, the difference is that you can do it anywhere. Compared to the previous alternative, it is visually better when inspecting code, because it outlines the start and end of msgclearly (compare with msg +=one every line, which needs one additional thinking step to deduce that those lines add to the same string - and what if you make a typo, forgetting a +on one random line ?).

请注意括号是如何用于允许我们不在纯字符串之间添加加号,并将结果扩展到多行而不需要显式续行 '\'(丑陋和混乱)。优点和下面描述的一样,不同的是你可以在任何地方做。与之前的替代方案相比,它在检查代码时在视觉上更好,因为它msg清楚地概述了开头和结尾(与msg +=每行一个相比,这需要一个额外的思考步骤来推断这些行添加到同一字符串中 - 以及如果你打错字了,+在一个随机的行上忘记了?)。

Regarding this approach, many times we have to build a string using iterations and checks within the iteration body, so adding its pieces within the function call, as shown later, is not an option.

关于这种方法,很多时候我们必须在迭代体中使用迭代和检查来构建一个字符串,因此在函数调用中添加它的部分,如下所示,不是一个选项。

A close alternative is:

一个接近的替代方案是:

msg = 'This message is so long, that it requires '
msg += 'many lines to write, one reason for that\n'
msg += 'is that it contains numbers, like this '
msg += 'one: ' + str(x) +', which take up more space\n'
msg += 'to insert. Note how newlines are also included '
msg += 'and can be better presented in the code itself.'
print(msg)

Though the first is preferable.

虽然第一个更可取。

The other approach is like the previous ones, though it starts the message on the line below the print. The reason for this is to gain space on the left, otherwise the print(itself "pushes" you to the right. This consumption of indentation is the inherited by the rest of the lines comprising the message, because according to PEP 8 they must align with the opening parenthesis of printabove them. So if your message was already long, this way it's forced to be spread over even more lines.

另一种方法与前面的方法类似,尽管它在print. 这样做的原因是要在左边获得空间,否则它print(本身会“推”你到右边。这种缩进的消耗是由包含消息的其余行继承的,因为根据 PEP 8,它们必须与print它们上方的左括号对齐。因此,如果您的消息已经很长,那么它会被迫分散到更多行中。

Contrast:

对比:

raise TypeError('aaaaaaaaaaaaaaaa' +
                'aaaaaaaaaaaaaaaa' +
                'aaaaaaaaaaaaaaaa')

with this (suggested here):

与此(建议here):

raise TypeError(
    'aaaaaaaaaaaaaaaaaaaaaaaa' +
    'aaaaaaaaaaaaaaaaaaaaaaaa')

The line spread was reduced. Of course this last approach does no apply so much to print, because it is a short call. But it does apply to exceptions.

线差减少了。当然,最后一种方法不适用于print,因为它是一个简短的调用。但它确实适用于例外情况。

A variation you can have is:

您可以拥有的变化是:

raise TypeError((
    'aaaaaaaaaaaaaaaaaaaaaaaa'
    'aaaaaaaaaaaaaaaaaaaaaaaa'
    'aaaaa {x} aaaaa').format(x=x))

Notice how you don't need to have plus signs between pure strings. Also, the indentation guides the reader's eyes, no stray parentheses hanging below to the left. The replacements are very readable. In particular, such an approach makes writing code that generates code or mathematical formulas a very pleasant task.

注意纯字符串之间不需要加号。此外,缩进引导读者的眼睛,左下方没有杂散的括号。替换是非常可读的。特别是,这种方法使编写生成代码或数学公式的代码成为一项非常愉快的任务。

回答by Taylor Edmiston

I'm surprised no one mentioned the implicit style above. My preference is to use parens to wrap the string while lining the string lines up visually. Personally I think this looks cleaner and more compact than starting the beginning of the string on a tabbed new line.

我很惊讶没有人提到上面的隐式风格。我的偏好是使用括号来包裹字符串,同时在视觉上将字符串对齐。就个人而言,我认为这比在选项卡式新行上开始字符串的开头看起来更简洁、更紧凑。

Note that these parens are not part of a method call —?they're only implicit string literal concatenation.

请注意,这些括号不是方法调用的一部分——它们只是隐式字符串文字连接

Python 2:

蟒蛇2:

def fun():
    print ('{0} Here is a really '
           'long sentence with {1}').format(3, 5)

Python 3 (with parens for print function):

Python 3(带有用于打印功能的括号):

def fun():
    print(('{0} Here is a really '
           'long sentence with {1}').format(3, 5))

Personally I think it's cleanest to separate concatenating the long string literal from printing it:

我个人认为将连接长字符串文字与打印它分开是最干净的:

def fun():
    s = ('{0} Here is a really '
         'long sentence with {1}').format(3, 5)
    print(s)