Multiline code - trailing slash usage

Steve Holden steve at holdenweb.com
Thu Mar 15 11:09:13 EDT 2007


abcd wrote:
> When do I need to use a trailing slash to separate code over multiple
> lines.
> 
> For example:
> 
> x = "hello world, this is my multiline " + \
>      "string!!!!"
> 
> x = {'name' : \
>       'bob'}
> 
> Do I need to use the "\" in the above examples?  When do i need to use
> it?
> 
It's only needed if the end of the line could also be the end of the 
statement. So if there's an unclosed parenthesis, bracket or brace you 
can move to the next line without using a continuation backslash.

So it's needed in the first example, but not in the second.

Note also, by the way, that the Python interpreter will concatenate two 
adjacent string literals, so you could also have written

x = "hello world, this is my multiline " \
      "string!!!!"

and this would have saved you a run-time string concatenation :)

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Blog of Note:          http://holdenweb.blogspot.com
See you at PyCon?         http://us.pycon.org/TX2007




More information about the Python-list mailing list