【问题标题】:How do you wrap text on IntelliJ(coding Python) when string is over 120 characters?当字符串超过 120 个字符时,如何在 IntelliJ(编码 Python)上换行?
【发布时间】:2017-11-06 22:00:31
【问题描述】:

我正在使用 IntelliJ 在 Python 中制作字典,第二个条目给我一个错误 PEP 8(line too long (155 > 120 characters)。

classic_common = {'Abusive Sergeant': 'ADD ME TO YOUR DECK, YOU MAGGOT!',
                  **'Acolyte of Pain': "He trained when he was younger to be an acolyte of joy, but things didn't work out like he thought they would",**

如何包装字符串,使其仍能正常工作并看起来可读。

谢谢。

【问题讨论】:

标签: python intellij-idea


【解决方案1】:

在不讨论如何让 IntelliJ 自动执行此操作的情况下,以下是关于如何在 Python 中换行长行(包括长字符串)的一般说明:

在 Python 中,可以使用explicitimplicit line joining 将单个语句写成多行。

在前者中,反斜杠('\',“行继续符”)用于表示一行的结束。例如(就像输入到 Python 解释器中一样):

>>> a = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 \
... + 9 + 10
>>> print(a)
55

另一方面,隐式行连接允许括号、方括号或花括号内的多行表达式自动连接在一起。换句话说,任何数量的空白在这些空间中都被视为相同。例如(出于说明目的使用不良风格):

>>> a = [1, 2, 3, 4, 5, 6  # comments are allowed too
... # as are empty lines
...
... # and even explicit line breaks
... \
... , 7, 8]
>>> print(a)
[1, 2, 3, 4, 5, 6, 7, 8]

事实证明,当您将键值对放在单独的行上时,您已经在代码 sn-p 中使用了隐式行连接。

除了隐式行连接之外,您还可以利用 Python 连接连续字符串且它们之间没有运算符的事实。再举一个例子:

>>> a = 'The quick brown' 'fox'
>>> b = 'The quick brown' + 'fox'
>>> print(a==b)
True

把这一切放在一起,因为你在花括号内,你可以在任何一点关闭你的字符串,然后将字符串的下一部分放在下一行的任何地方。括号中的空白不可知论意味着您可以对齐字符串每行的开头(注意下面的“He”、“of”和“thought”是如何对齐的)。

因此你能得到类似the answer from idjaw's comment:

>>> classic_common = {'Abusive Sergeant': 'ADD ME TO YOUR DECK, YOU MAGGOT!',
                      'Acolyte of Pain': "He trained when he was younger to be an acolyte " 
                                         "of joy, but things didn't work out like he " 
                                         "thought they would",
                      'some_other_key': 'some other value'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-08
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2019-06-11
    • 2021-04-06
    • 1970-01-01
    相关资源
    最近更新 更多