Python中的字符串连接 [英] String concatenation in Python

查看:152
本文介绍了Python中的字符串连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以描述两种字符串连接方式的区别:简单 __ add __ 运算符和%s 模式?
我在这个问题上进行了一些调查,发现%s (不使用括号)。

Can you describe difference between two ways of string concatenation: simple __add__ operator and %s patterns? I had some investigation in this question and found %s (in form without using parentheses) a little faster.

另一个问题出现了:为什么'hell%s'%'o'的结果是指 s'%('o',)

Also another question was appeared: why result of 'hell%s' % 'o' refers to another memory region than 'hell%s' % ('o',)?

有一些代码示例:

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

结果:

[34375618400, 34375618400, 34375618400, 34375626256]

PS我知道字符串实习:)

P.S. I know about string interning :)

推荐答案

这是一个小练习:

>>> 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         

如你所见,所有简单的连接/格式化都是由编译器完成的。最后一个函数需要更复杂的格式,因此,我想,实际上是执行。由于所有在编译时创建的对象都具有相同的ID。

As you can see, all simple concatenations/formatting are done by compiler. The last function requires more complex formatting and therefore, I guess, is actually executed. Since all those object created at compilation time they all have the same id.

这篇关于Python中的字符串连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆