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

来源:互联网 发布:编程初学 编辑:程序博客网 时间:2024/06/06 10:53

用三中方法实现字符串的拼接:

其中第一种方法是每加一次,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

原创粉丝点击