str1 = 'this is a very long string.\n' +\In this first way, it is annoying that you need to type extra characters each line,
'second line of the string.'
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.They all yield the same Python string. But this method can look very ugly because it can violate the indentation in the source code.
second line of the string.'''
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."])
ReplyDeleteGreat article by the great author, it is very massive and informative but still preaches the way to sounds like that it has s
python string methods