字符串连接的三种方法比较

python 字符串连接的方法,一般有三种:The way 1: 直接通过加号操作符连接 The way 2: join方法 The way 3:替换

方法 一:加号连接(+)

1 webist = "www." + "baidu." + "com"
View Code

方法 二:join方法

listStr = ['pyhton', 'tab', '.com']
websit = ' '.join(listStr)

方法 三:替换

websitr = '%s%s%s' % ('python', 'tab', '.com')

方法1,使用简单直接,但是网上不少人说这种方法效率低

之所以说python 中使用 + 进行字符串连接的操作效率低下,是因为python中字符串是不可变的类型,使用 + 连接两个字符串时会生成一个新的字符串,生成新的字符串就需要重新申请内存,当连续相加的字符串很多时(a+b+c+d+e+f+...) ,效率低下就是必然的了

方法2,使用略复杂,但对多个字符进行连接时效率高,只会有一次内存的申请。而且如果是对list的字符进行连接的时候,这种方法必须是首选

#!/usr/bin/env python  
# -*- coding:utf-8 -*-  
  
import os,sys  
import time  
  
MAX = 9000000  
char_list = [ chr((i % 26) +97)  for i in xrange(MAX) ]  
  
my_str=''  
last_time = time.time()  
for i in char_list:  
    my_str = my_str + i  
print time.time() - last_time  
print '-' * 80  
  
  
my_str=''  
t_list=[]  
last_time =  time.time()  
for i in char_list:  
    t_list.append(i)  
my_str = ''.join(t_list)  
print time.time() - last_time  
print '-' * 80  

结果:9.316163539886475/2.0593628883361816

 -*- coding: utf-8 -*-
from time import time
def method1():
    t = time()
    for i in xrange(100000):
        s = 'pythontab'+'pythontab'+'pythontab'+'pythontab'
    print time() - t
def method2():
    t = time()
    for i in xrange(100000):
        s = ''.join(['pythontab','pythontab','pythontab','pythontab'])
    print time() -t
method1()
method2()

结果:

0.00099945068359375
0.0380253791809082

原文地址:https://www.cnblogs.com/Davirain/p/8777475.html