如何编写符合PEP8的非常长的字符串并阻止E501

时间:2009-12-09 15:20:55

标签: python string pep8

由于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."

13 个答案:

答案 0 :(得分:244)

另外,因为相邻字符串常量是自动连接的,所以你也可以这样编码:

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”。

答案 1 :(得分:91)

隐式连接可能是最干净的解决方案:

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

编辑经过反思,我同意托德建议使用括号而不是续行是因为他给出的所有原因都更好。我唯一的犹豫是将括号中的字符串与元组混淆相对容易。

答案 2 :(得分:14)

我认为你问题中最重要的一个词是“建议”。

编码标准很有趣。通常,它们提供的指导在编写时具有非常好的基础(例如,大多数终端无法在一条线上显示> 80个字符),但随着时间的推移,它们在功能上已经过时,但仍然严格遵守。我想你需要做的就是权衡“打破”特定建议与代码的可读性和可维护性的相对优点。

对不起,这不能直接回答你的问题。

答案 3 :(得分:13)

你失去了一个空间,你可能需要一个续行字符,即。 \

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."
Parens也可以工作而不是续行,但你冒险有人认为你打算有一个元组并且忘记了一个逗号。举个例子:

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.")

使用Python的动态类型编码,代码可能以任何一种方式运行,但会产生与您不想要的结果不正确的结果。

答案 4 :(得分:3)

反斜杠:

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

或包裹在parens中:

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

答案 5 :(得分:0)

使用\,您可以将语句扩展为多行:

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

应该有用。

答案 6 :(得分:0)

这些都是很好的答案,但是我找不到能帮助我编辑“隐式连接”字符串的编辑器插件,因此我编写了一个程序包使之更容易使用。

在pip(安装段落)上,如果有人在徘徊这个旧线程想要将其检出。像html一样格式化多行字符串(压缩空格,为新段落添加两个换行符,不用担心行之间的空格)。

from paragraphs import par

class SuddenDeathError(Exception):
    def __init__(self, cause: str) -> None:
        self.cause = cause

    def __str__(self):
par(
    f"""
    Y - e - e - e - es, Lord love you! Why should she die of
    influenza? She come through diphtheria right enough the year
    before. I saw her with my own eyes. Fairly blue with it, she was.They
    all thought she was dead; but my father he kept ladling gin down
    her throat til she came to so sudden that she bit the bowl off the
    spoon. 

    What call would a woman with that strength in her have to die of
    influenze? What become of her new straw hat that should have
    come to me? Somebody pinched it; and what I say is, them as pinched
    it done her in."""
)

成为...

Y - e - e - e - es, Lord love you! Why should she die of influenza? She come through...

What call would a woman with that strength in her have to die of influenza?  What...

使用(Vim)'gq',一切都很轻松

答案 7 :(得分:0)

可用选项:

  • 反斜杠"foo" \ "bar"
  • 加号,后跟反斜杠"foo" + \ "bar"
  • 括号
    • ("foo" "bar")
    • 括号,带有加号("foo" + "bar")
    • PEP8,E502:括号之间的反斜杠是多余的

避免

请避免使用括号("foo", "bar")来定义元组。


>>> s = "a" \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
>>> s = "a" + \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
>>> s = ("a"
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>> s = ("a",
... "b")
>>> type(s)
<class 'tuple'>
>>> s = ("a" + 
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>> 

答案 8 :(得分:0)

使用 black [https://github.com/psf/black] 我这样格式化。

   help=f"""filters, lista de filtros para cargar las base de conocimiento.
   Pueden mandarse solo algunos filtros ya que no son obligatorios,
   por ejemplo, si no se manda sts, se cargarán todos las bases de todos los estados.""",

答案 9 :(得分:0)

message = f"Variable : child({type(child)}) -> is not of"\
        " type Node."

这种语法对我有用。注意第二个语句的缩进,应该正确缩进。

答案 10 :(得分:-1)

我倾向于使用一些此处未提及的方法来指定大字符串,但这是针对非常特殊的情况的。 YMMV ...

  • 多行文本,通常带有格式化的标记(不是您所要的,但仍然有用):

    error_message = '''
    I generally like to see how my helpful, sometimes multi-line error
    messages will look against the left border.
    '''.strip()
    
  • 通过您喜欢的任何字符串插值方法逐段增加变量:

    var = 'This is the start of a very,'
    var = f'{var} very long string which could'
    var = f'{var} contain a ridiculous number'
    var = f'{var} of words.'
    
  • 从文件中读取它。 PEP-8不会限制文件中字符串的长度;只是您的代码行。 :)

  • 使用蛮力或您的编辑器使用换行符将字符串拆分为可换行,然后删除所有换行符。 (类似于我列出的第一种技术):

    foo = '''
    agreatbigstringthatyoudonotwanttohaveanyne
    wlinesinbutforsomereasonyouneedtospecifyit
    verbatimintheactualcodejustlikethis
    '''.replace('\n', '')
    

答案 11 :(得分:-1)

我过去使用过textwrap.dedent。这有点麻烦,所以我现在更喜欢连续行,但是如果您真的想要块缩进,我认为这很棒。

示例代码(其中的修饰是去除带有切片的第一个'\ n'):

import textwrap as tw
x = """
       This is a yet another test.
       This is only a test"""
print(tw.dedent(x[1:]))

说明:

据我所知,dedent根据换行之前第一行文本中的空格来计算缩进。因此,我添加了一个换行符,以便于排队代码。为了避免换行,您必须在文本的第一行中添加额外的空格,以便后续行的缩进量可以根据需要减少。如果您想对其进行调整,则可以使用re模块轻松地重新实现它。

此方法有局限性,因为很长的行仍然比您想要的更长,在这种情况下,其他将字符串连接的方法更合适。

答案 12 :(得分:-1)

如果必须插入长字符串文字并且要关闭flake8,则可以使用shutting up directives。例如,在测试例程中,我定义了一些伪造的CSV输入。我发现将它分割成行的更多行会造成极大的混乱,因此我决定添加一个# noqa: E501如下:

csv_test_content = """"STATION","DATE","SOURCE","LATITUDE","LONGITUDE","ELEVATION","NAME","REPORT_TYPE","CALL_SIGN","QUALITY_CONTROL","WND","CIG","VIS","TMP","DEW","SLP","AA1","AA2","AY1","AY2","GF1","MW1","REM"
"94733099999","2019-01-03T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","050,1,N,0010,1","22000,1,9,N","025000,1,9,9","+0260,1","+0210,1","99999,9","24,0000,9,1",,"0,1,02,1","0,1,02,1","01,99,1,99,9,99,9,99999,9,99,9,99,9","01,1","SYN05294733 11/75 10502 10260 20210 60004 70100 333 70000="
"94733099999","2019-01-04T04:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","090,1,N,0021,1","22000,1,9,N","025000,1,9,9","+0378,1","+0172,1","99999,9","06,0000,9,1",,"0,1,02,1","0,1,02,1","03,99,1,99,9,99,9,99999,9,99,9,99,9","03,1","SYN04294733 11/75 30904 10378 20172 60001 70300="
"94733099999","2019-01-04T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","290,1,N,0057,1","99999,9,9,N","020000,1,9,9","+0339,1","+0201,1","99999,9","24,0000,9,1",,"0,1,02,1","0,1,02,1",,"02,1","SYN05294733 11970 02911 10339 20201 60004 70200 333 70000="
"94733099999","2019-01-05T22:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","200,1,N,0026,1","99999,9,9,N","000100,1,9,9","+0209,1","+0193,1","99999,9","24,0004,3,1",,"1,1,02,1","1,1,02,1","08,99,1,99,9,99,9,99999,9,99,9,99,9","51,1","SYN05294733 11/01 82005 10209 20193 69944 75111 333 70004="
"94733099999","2019-01-08T04:00:00","4","-32.5833333","151.1666666","45.0","SINGLETON STP, AS","FM-12","99999","V020","070,1,N,0026,1","22000,1,9,N","025000,1,9,9","+0344,1","+0213,1","99999,9","06,0000,9,1",,"2,1,02,1","2,1,02,1","04,99,1,99,9,99,9,99999,9,99,9,99,9","02,1","SYN04294733 11/75 40705 10344 20213 60001 70222="
"""  # noqa: E501