Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variants of string concatenation?

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

  • What's the preferred way?
  • What's the difference?
  • When should one or the other be used?
  • Should non of them ever be used, if so why?
  • Is 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
like image 560
UlfR Avatar asked Dec 08 '15 14:12

UlfR


Video Answer


2 Answers

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'
like image 138
Mike Müller Avatar answered Oct 13 '22 12:10

Mike Müller


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.

like image 29
Maciek Avatar answered Oct 13 '22 11:10

Maciek