Out of the following two variants (with or without plus-sign between) of string literal concatenation:
join
preferred?Code:
>>> # variant 1. Plus
>>> 'A'+'B'
'AB'
>>> # variant 2. Just a blank space
>>> 'A' 'B'
'AB'
>>> # They seems to be both equal
>>> 'A'+'B' == 'A' 'B'
True
Juxtaposing works only for string literals:
>>> 'A' 'B'
'AB'
If you work with string objects:
>>> a = 'A'
>>> b = 'B'
you need to use a different method:
>>> a b
a b
^
SyntaxError: invalid syntax
>>> a + b
'AB'
The +
is a bit more obvious than just putting literals next to each other.
One use of the first method is to split long texts over several lines, keeping indentation in the source code:
>>> a = 5
>>> if a == 5:
text = ('This is a long string'
' that I can continue on the next line.')
>>> text
'This is a long string that I can continue on the next line.'
''join()
is the preferred way to concatenate more strings, for example in a list:
>>> ''.join(['A', 'B', 'C', 'D'])
'ABCD'
The variant without +
is done during the syntax parsing of the code. I guess it was done to let you write multiple line strings nicer in your code, so you can do:
test = "This is a line that is " \
"too long to fit nicely on the screen."
I guess that when it's possible, you should use the non-+
version, because in the byte code there will be only the resulting string, no sign of concatenation left.
When you use +
, you have two string in your code and you execute the concatenation during runtime (unless interpreters are smart and optimize it, but I don't know if they do).
Obviously, you cannot do: a = 'A' ba = 'B' a
Which one is faster? The no-+
version, because it is done before even executing the script.
+
vs join
-> If you have a lot of elements, join
is prefered because it is optimised to handle many elements. Using + to concat multiple strings creates a lot of partial results in the process memory, while using join
doesn't.
If you're going to concat just a couple of elements I guess +
is better as it's more readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With