方法一:+
s1="hello"
s2="world"
s3=s1+s2
print(s3)
方法二:join
str.join(sequence)
sequence -- 要連接的元素序列。
示例:
s1="-"
s2=['hello','world']
s3=s1.join(s2)
print(s3)
方法三:用%符號拼接
s1="hello"
s2="world"
s3="%s-%s"%(s1,s2)
print(s3)
方法四:format連接
s1="hello"
s2="world"
s3="{0}-{1}".format(s1,s2)
print(s3)
方法五:string模塊的Template
from string import Template
fruit1 ="apple"
fruit2 ="banana"
fruit3 ="pear"
str = Template('There are ${fruit1}, ${fruit2}, ${fruit3} on the table')
print(str.safe_substitute(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3))
print(str.safe_substitute(fruit1=fruit1,fruit2=fruit2,fruit3=fruit3) )
效率比較:+號和join
結(jié)論:join的性能遠(yuǎn)高于+
原因:1)使用 + 進(jìn)行字符串連接的操作效率低下禁荒,是因為python中字符串是不可變的類型,使用 + 連接兩個字符串時會生成一個新的字符串,生成新的字符串就需要重新申請內(nèi)存榄审,當(dāng)連續(xù)相加的字符串很多時(a+b+c+d+e+f+...) 链患,效率低下就是必然的了。2)join使用比較麻煩蛹批,但對多個字符進(jìn)行連接時效率高仰泻,只會有一次內(nèi)存的申請荆陆。而且如果是對list的字符進(jìn)行連接的時候,這種方法必須是首選
示例佐證:
import time
def decorator(func):
? ? def wrapper(*args, **kwargs):
? ? ? ? start_time = time.time()
? ? ? ? func()
? ? ? ? end_time = time.time()
? ? ? ? print(end_time - start_time)
? ? return wrapper
@decorator
def method_1():
? ? s = ""
? ? for i in range(1000000):
? ? ? ? s += str(i)
@decorator
def method_2():
? ? l = [str(i) for i in range(1000000)]
? ? s = "".join(l)
method_1()
method_2()
結(jié)果:
1.940999984741211
0.2709999084472656