1

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?

snakile
  • 52,936
  • 62
  • 169
  • 241

2 Answers2

5

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'
>>> 
Community
  • 1
  • 1
gimel
  • 83,368
  • 10
  • 76
  • 104
4

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'
David Webb
  • 190,537
  • 57
  • 313
  • 299
  • Thanks. The backslash is what I was looking for – snakile Aug 13 '10 at 14:13
  • @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 Aug 13 '10 at 14:21
  • You can escape the newlines in `"""` strings with the `\ `. – Wayne Werner Aug 13 '10 at 14:24
  • @Nick T Agreed. That's why I accepted the parenthesis solution (but still upvoted that one because it's also good) – snakile Aug 13 '10 at 14:28