views:

72

answers:

2

I have a variable x to which I want to assign a very long string. Since the string is pretty long I split it into 10 substrings. I would like to do something like this:

x =
   'a very long string - part 1'+
   'a very long string - part 2'+
   'a very long string - part 3'+
                ...
   'a very long string - part 10'

But turns out this is an invalid syntax. What is the valid syntax for that?

+4  A: 

Usually Python will spot that one line continues to the next but if it doesn't put a backslash at the end of each line:

>>> x = 'a' + \
...     'b' + \
...     'c'
>>> x
'abc'

Or use standard syntax like brackets to make it clear:

>>> x = ('a' +
...      'b' +
...      'c')
>>> x
'abc'

You can create a long string using triple quotes - """ - but note that any news lines will be included in the string.

>>> x = """a very long string part 1
... a very long string part 2
... a very long string part 3
... a very long string part 4"""
>>> x
'a very long string part 1\na very long string part 2\na very long string part 3\na very long string part 4'
Dave Webb
Thanks. The backslash is what I was looking for
snakile
@snakile I personally try to avoid the backslash (and use parenthesis `()` or similar) because you can mindlessly add a new line without having to remember the `\\`. Also, if you have any whitespace after the continuation character it will throw errors.
Nick T
You can escape the newlines in `"""` strings with the `\ `.
Wayne Werner
@Nick T Agreed. That's why I accepted the parenthesis solution (but still upvoted that one because it's also good)
snakile
+4  A: 

If you want a string with no line-feeds, you could

>>> x = (
... 'a very long string - part 1' +
... 'a very long string - part 2' +
... 'a very long string - part 3' )
>>> x
'a very long string - part 1a very long string - part 2a very long string - part 3'
>>> 

The + operator is not necessary with string literals:

2.4.2. String literal concatenation

Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld". This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings, for example:

re.compile("[A-Za-z_]"       # letter or underscore
       "[A-Za-z0-9_]*"   # letter, digit or underscore
      )

Your case:

>>> x = (
... 'a very long string - part 1' 
... 'a very long string - part 2' 
... 'a very long string - part 3' )
>>> x
'a very long string - part 1a very long string - part 2a very long string - part 3'
>>> 
gimel
+1 for the solution without the `+` operator
igor