我应该如何编写很长的代码?
如果我有很长的一行代码,是否可以在下一行继续它,例如:
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:'
if i have a very long line of a code, is it possible to continue it on the next line for example:
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:'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会这样写
请注意,不需要
+
来连接字符串。这种方式更好,因为字符串是在编译时而不是运行时连接的。我还在您的字符串中嵌入了
%(max_freq)s
,这是从末尾的dict
中替换的另请查看
urllib.urlencode()
如果你想让你的 url 处理更简单I would write it like this
Note that the
+
are not required to join the strings. It is better this way because the strings are joined at compile time instead of runtime.I've also embedded
%(max_freq)s
in your string, this is substituted in from thedict
at the endAlso check out
urllib.urlencode()
if you want to make your url handling simpler将来到哪里寻求帮助
大多数像这样的语法问题都在 PEP 8。这个问题的答案可以参考“代码布局”一节。
首选方式:使用
()
,{}
&[]
来自 PEP-8:
这意味着您的示例将像这样:
替代方法:使用
\
From PEP-8:
避免串联
字符串格式
在本例中,我们只想在 URL 中更改一件事:
max(freq)
。为了有效地将其插入到新字符串中,我们可以使用带有数字或命名参数的format
方法:Where to look for help in future
Most syntax problems like this are dealt with in PEP 8. For the answer to this question, you can refer to the section "Code Layout".
Preferred way : Use
()
,{}
&[]
From PEP-8:
This means your example would like like this:
The alternate way: Use
\
From PEP-8:
Avoiding concatenation
String formatting
In this case, we only have a single thing that we would like to be changed in the URL:
max(freq)
. In order to efficiently insert this into a new string, we can use theformat
method with numerical or named arguments:Python 将两个字符串文字组合在一起,
但如果它们位于两行,则不起作用,因为 Python 不知道下一行是命令的一部分。要解决这个问题,您可以使用反斜杠或方括号。
并且您不需要
+
将字符串连接在一起。您仍然需要它来添加像max(freq)
这样的非文字,如 字符串文字连接。这稍微更高效,但更重要的是更清晰,并且可以对字符串的部分进行注释,如链接的 Python 文档中所示。Python combines two strings literal together, so
but that wouldn't work if they are on two lines because Python doesn't know that the next line is part of the command. To solve that you can use backslash or brackets.
and you wouldn't need
+
to attach the strings together. You will still need it for adding nonliterals likemax(freq)
, as explained in String Literal Concatenation. This is marginally more efficient, but more importantly clearer and enables commenting parts of a string as shown in the Python documentation linked.是的,使用反斜杠
\
,如下所示:或者您可以用括号
()
将表达式括起来:Yes, use a backslash
\
, like so:Or you can wrap your expression with parentheses
()
: