views:

201

answers:

4

What does the +\ 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.

+7  A: 

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

Gary
+15  A: 

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

Ignacio Vazquez-Abrams
Damn you all for beating me to it ;)
Nathan Tomkins
And the funny thing is that the `\\` isn't even necessary in this case.
Tim Pietzcker
This is true. The Python parser can unambiguously determine that the expression must continue on the next line due to the fact that not all "groupings" (parens in this case) have been closed.
Ignacio Vazquez-Abrams
And the funny thing is that the "+" is not even necessary either, as strings that follow each other are automatically concatenated!! (as Dave pointed out)
EOL
It is in this case, due to the placement of the modulus operator.
Ignacio Vazquez-Abrams
+10  A: 

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( )
Dave Kirby
+1  A: 

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

gnibbler