开发者

+\ operator in Python

What does th开发者_Python百科e +\ operator do in Python?

I came across this piece of code -

rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'+\
's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996'%t +\
'&ignore=.csv').readlines( )

and can't find any references that explain it.


The + is addition. The \ at the end of the line continues the current statement or expression on the next line.


N.B. The \ continuation is unnecessary in this case since the expression is inside parentheses. Python is smart enough to know that a line continues until all brackets, braces and parentheses are balanced.

Unnecessary continuation characters are a minor bugbear of mine, and I delete them at every opportunity. They clutter the code, confuse newbies who think they are some kind of operator and can be invisibly broken by accidentally putting a space after them.

Also the first + character is unnecessary - Python will concatenate string literals automatically.

I would also move the % operator to the end of the expression and eliminate the second +, so the line could be rewritten as:

rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'
                     's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996' 
                     '&ignore=.csv' % t).readlines( )


It's not an operator, it's just the + operator followed by the line continuation \


You can rewrite your code like so

rows=urllib2.urlopen('http://ichart.finance.yahoo.com/table.csv?'
                     's=%s&d=11&e=26&f=2006&g=d&a=3&b=12&c=1996'
                     '&ignore=.csv'%t).readlines()

The parser joins the lines together into one, so you are not wasting time by uselessly adding strings together at runtime

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜