您的位置:首页 > 编程语言 > Python开发

python三种方法实现字符串拼接

2017-11-14 00:45 676 查看
用三中方法实现字符串的拼接:

其中第一种方法是每加一次,Python内部都会开辟一个新的空间用于存放,这样会造成资源的浪费和时间的消耗(不推荐使用这种方法)

第二种用%s进行字符串的拼接,在少量字符串拼接中是比较快的,也并不会浪费过多资源,但是拼接量过大在时间上会有劣势(少量字符串拼接建议使用这种方式)

第三种用join内置方法实现拼接,在少量字符串拼接时速度略差于第二种方法,如果大量的字符串拼接则优于第二种(适合大量字符串拼接)

#字符串拼接的三种方法:
#第一种直接相加:
def methodfirst():
en_list = ['this','is','a','sentence','!']
result = ""
for i in range(len(en_list)):
result = en_list[i] + result
print(result)
#第二种方法用%s组成字符串
def methodsecond():
a = "ncwx."
b = "gcu."
c = "edu."
d = "cn"
print("website: %s%s%s%s"%(a,b,c,d))
#用join方法实现字符串的连接
def methodththird():
name = ['w','u','l','e','i']
name_result1 = "_".join(name)
name_result2 = "".join(name)
print(name_result1)
print(name_result2)

methodfirst()
methodsecond()
methodththird()


结果:

S:\python\python3\setup\python3.exe W:/python/Helloworld/ProgramOne/str_study.py

!sentenceaisthis

website: ncwx.gcu.edu.cn

w_u_l_e_i

wulei

进程已结束,退出代码0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 字符串