String concatenation options?

Of the following two options (with or without a plus sign) between the concatenation of string literals:

  • What is the preferred way?
  • What's the difference?
  • When to use one or the other?
  • If they are not used, if so, why?
  • Do you prefer join ?

the 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 
+8
python string string-concatenation
source share
2 answers

Mapping only works for string literals:

 >>> 'A' 'B' 'AB' 

If you work with string objects:

 >>> a = 'A' >>> b = 'B' 

you need to use another method:

 >>> ab ab ^ SyntaxError: invalid syntax >>> a + b 'AB' 

+ little more obvious than just placing literals next to each other.

One use of the first method is to split long texts into several lines while preserving the indent 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' 
+13
source share

The option without + is executed during parsing of the code. I assume this was done to allow you to write multiple lines in a row in your code so that you can:

 test = "This is a line that is " \ "too long to fit nicely on the screen." 

I assume that when possible, you should use the non-+ version, because there will only be a result string in the byte code, no signs of concatenation remain.

When you use + , you have two lines in the code, and you do concatenation at runtime (unless the 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? Version no-+ , as it is executed before the script is executed.

+ vs join โ†’ If you have many elements, join is preferred because it is optimized to handle many elements. Using + to concat multiple lines creates many partial results in process memory, but using join does not.

If you are going to use only a couple of elements, I think + better, since it is more readable.

+1
source share

All Articles