[Tutor] mistaken about splitting expressions over lines

Dave Angel davea at davea.name
Tue Jun 25 03:58:14 CEST 2013


On 06/24/2013 09:48 PM, Jim Mooney wrote:
> For some reason I took the impression that you could split expressions
> over lines. However, this works:
>
> word = 'spam'
> new_word = word + 'eggs'
> print(word)
>
> But this is a syntax error:
>
> word = 'spam'
> new_word = word +
> 'eggs'
> print(word)
>
>   That's easy to avoid, but what if you're adding five or six very long
> things, like some really long strings?
>

Simplest thing is to add parentheses around the expression.

   new_word = (word + 'a very long string' + other_word +
               "another long string" + still_another)

Alternatively, you can also use the statement continuation mechanism, 
whereby the last character of the line is a backslash.  Using that 
approach you can break almost anywhere, except within a token or inside 
a string literal.  And you can break up string literals without using a 
"+" operator, because adjacent string literals are combined at compile time.

   a = "this" \
       " string" " is long"

is exactly equivalent to
   a = "this string is long"


-- 
DaveA


More information about the Tutor mailing list