UlfR
UlfR

Reputation: 4395

Variants of string concatenation?

Out of the following two variants (with or without plus-sign between) of string literal concatenation:

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

Upvotes: 8

Views: 1394

Answers (2)

Maciek
Maciek

Reputation: 3234

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.

Upvotes: 1

Mike Müller
Mike Müller

Reputation: 85442

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'

Upvotes: 13

Related Questions