Wednesday, September 21, 2011

Python multi-line strings

There are several ways to compose a Python string literal in multiple lines if the string is too long. One way is to use the add operator. For example:
str1 = 'this is a very long string.\n' +\
'second line of the string.'
In this first way, it is annoying that you need to type extra characters each line,
i.e. the plus operator and line continuation mark. Another way you can do this is to use the triple-quotes ''' or """:
str2 = '''this is a very long string.
second line of the string.'''
They all yield the same Python string. But this method can look very ugly because it can violate the indentation in the source code.

In Python if you just put two string literals together, with or without spaces in between, your result string will be the concatenated string of all the strings. For example:
str3 = 'this ' 'is ' 'a ' 'string.'
and value of str3 will be:
'this is a string.'
Thus, my preferred way of doing this is to use the implicit line continuation by parentheses, with the implicit string concatenation. For example:

str4 = ('this is a very long string.\n'
        'second line of the string.'
       )

This will give you the same result of the first two examples.

Nice, isn't it?

Update:

There was a PEP 3126 that suggests implicit string concatenation to be removed from Python 3, but it has been rejected. I tested this in Python 3 and it still works. But the document also suggests a good way to do this with the join function:
"\n".join(["this is a very long string.",
"second line of the string."])