python:我应该怎么写很长的代码行?

l--*_*''' 13 python pep8

如果我有一个很长的代码行,是否可以在下一行继续它,例如:

 url='http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|'
+ '100,000|1,000,000&chxp=1,0&chxr=0,0,' +
      max(freq) + '300|1,0,3&chxs=0,676767,13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1,0&chs=640x465&cht=bvs&chco=A2C180&chds=0,300&chd=t:'
Run Code Online (Sandbox Code Playgroud)

Joh*_*ooy 21

我会这样写的

url=('http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|'
     '100,000|1,000,000&chxp=1,0&chxr=0,0,%(max_freq)s300|1,0,3&chxs=0,676767'
     ',13.5,0,l,676767|1,676767,13.5,0,l,676767&chxt=y,x&chbh=a,1,0&chs=640x465'
     '&cht=bvs&chco=A2C180&chds=0,300&chd=t:'%{'max_freq': max(freq)})
Run Code Online (Sandbox Code Playgroud)

请注意,+不需要加入字符串.这种方式更好,因为字符串在编译时而不是运行时连接.

我也嵌入%(max_freq)s了你的字符串,这是从dict最后的代替

另外,请查看urllib.urlencode()是否要使您的网址处理更简单


Tim*_*ara 16

今后在哪里寻求帮助

像这样的大多数语法问题都在PEP 8中处理.有关此问题的答案,请参阅"代码布局"部分.

首选方式:使用(),{}&[]

从PEP-8:

包装长行的首选方法是在括号,括号和括号内使用Python隐含的行继续.如有必要,您可以在表达式周围添加一对额外的括号...

这意味着你的例子是这样的:

url= ('http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|' +
      '100,000|1,000,000&chxp=1,0&chxr=0,0,' +
      max(freq) + 
      '300|1,0,3&...chco=A2C180&chds=0,300&chd=t:')
Run Code Online (Sandbox Code Playgroud)

替代方式:使用 \

从PEP-8:

...但有时使用反斜杠看起来更好.确保适当缩进续行.

url = 'http://chart.apis.google.com/chart?chxl=1:|0|10|100|1,000|10,000|' + \
      '100,000|1,000,000&chxp=1,0&chxr=0,0,' + \ 
       max(freq) + \
      '300|1,0,3&...chco=A2C180&chds=0,300&chd=t:'
Run Code Online (Sandbox Code Playgroud)

避免连接

字符串格式

在这种情况下,我们只想在URL中更改一件事:max(freq).为了有效地将其插入到新字符串中,我们可以使用format带有数字或命名参数的方法:

url = "http://...{0}.../".format(max(freq))
url = "http://...{max_freq}.../".format(max_freq=max(freq))
Run Code Online (Sandbox Code Playgroud)