**方法1:**直接通过加号(+)操作符连接website=& 39;python& 39;+& 39;tab& 39;+& 39; com& 39;
**方法2:**python字符串连接的方法,一般有以下三种:
website = 'python' + 'baidu' + '.com'
listStr = ['python', 'baidu', '.com'] website = ''.join(listStr)
website = '%s%s%s' % ('python', 'baidu', '.com')
下面用实验来说明字符串连接的效率问题。
案例一:
''' 学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:660193417 寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书! ''' from time import time def method1(): t = time() for i in range(100000): s = 'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python'+'python' print (time() - t) def method2(): t = time() for i in range(100000): s = ''.join(['python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python','python']) print (time() -t) method1() method2()
结果:
0.0029921531677246094 0.09973287582397461
案例二:
''' 学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:660193417 寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书! ''' from time import time def method1(): t = time() for i in range(100000): s = 'python'+'python'+'python'+'python' print (time() - t) def method2(): t = time() for i in range(100000): s = ''.join(['python','python','python','python']) print (time() -t) method1() method2()
结果:
0.002992391586303711 0.01495981216430664
上面两个实验出现了完全不同的结果,分析这两个实验唯一不同的是:字符串连接个数。
结论:加号连接效率低是在连续进行多个字符串连接的时候出现的,如果连接的个数较少,加号连接效率反而比join连接效率高