Why does python join two String
without any kind of operator such as addition?
This:
>>> 'Perro' 'Lobo'
'PerroLobo'
It does the same as this:
>>> 'Perro' + 'Lobo'
'PerroLobo'
Why does python join two String
without any kind of operator such as addition?
This:
>>> 'Perro' 'Lobo'
'PerroLobo'
It does the same as this:
>>> 'Perro' + 'Lobo'
'PerroLobo'
Well, when a programming language does something like that, it's usually by design. In this case, as explained in the documentation :
Translated:
A typical use for this feature is to create long strings that won't fit on one line.
Python has the ability to use the "triple quote" to delimit multi-line strings, for example like so:
The resulting string also contains carriage returns, as you can see if you inspect it in the shell:
You may not want the carriage returns to be part of the string. With the triple quote you have no way around it.
An additional problem is that the string formatted in this way breaks the indentation of the source. It's not a bug for Python, but it does make it difficult to read. Let's not say if the string in question appears inside another block that is indented, such as:
This completely breaks readability (although python supports it). It would be much better like this:
The problem is that by doing this, all the spaces that we have used to indent the string remain part of it:
We see then that the triple quote, although it allows writing long strings by separating them into several lines in the source, poses two problems:
To solve both problems we can use this trick:
Putting it in parentheses is a trick for python to allow me to break an expression across multiple lines. Once a parenthesis is open, as long as it is not closed, Python supports carriage returns and any indentation within. It is therefore equivalent to having put the three strings next to each other on the same line (note that I have not put commas after each string, since then it would be a tuple).
Since Python will concatenate them into one, the result is equivalent to the triple quote example, only now neither the carriage returns nor the spaces in the indent are part of the string.
If you want carriage returns to be part of the resulting string, you can manually put them (
"\n"
) inside each chunk: