Python string concatenation

Can you describe the difference between two ways to concatenate strings: a simple operator __add__and %spatterns? I had some kind of investigation on this and I found %s(in the form without using brackets) a little faster.

Another question also arose: why does the result 'hell%s' % 'o'relate to a different area of ​​memory than 'hell%s' % ('o',)?

There are several code examples:

l = ['hello', 'hell' + 'o', 'hell%s' % 'o', 'hell%s' % ('o',)]
print [id(s) for s in l]

Result:

[34375618400, 34375618400, 34375618400, 34375626256]

PS I know how to do string interning :)

+3
source share
2 answers

Here is a little exercise:

>>> def f1():
    'hello'


>>> def f2():
    'hel' 'lo'


>>> def f3():
    'hel' + 'lo'


>>> def f4():
    'hel%s' % 'lo'


>>> def f5():
    'hel%s' % ('lo',)


>>> for f in (f1, f2, f3, f4, f5):
    print(f.__name__)
    dis.dis(f)


f1
  1           0 LOAD_CONST               1 (None) 
              3 RETURN_VALUE         
f2
  1           0 LOAD_CONST               1 (None) 
              3 RETURN_VALUE         
f3
  2           0 LOAD_CONST               3 ('hello') 
              3 POP_TOP              
              4 LOAD_CONST               0 (None) 
              7 RETURN_VALUE         
f4
  2           0 LOAD_CONST               3 ('hello') 
              3 POP_TOP              
              4 LOAD_CONST               0 (None) 
              7 RETURN_VALUE         
f5
  2           0 LOAD_CONST               1 ('hel%s') 
              3 LOAD_CONST               3 (('lo',)) 
              6 BINARY_MODULO        
              7 POP_TOP              
              8 LOAD_CONST               0 (None) 
             11 RETURN_VALUE         

, / . , , , . , , .

+7

% , , , . .

, , , , . , - , .

100%, , , C - , ''.join(sequence), + - . .

* .

+1

Source: https://habr.com/ru/post/1757343/


All Articles