Python_字符串连接

 1 #join() 与split()相反,join()方法用来将列表中多个字符串进行连接,并在相邻两个字符串之间插入指定字符
 2 li=['apple','peach','banana','pear']
 3 sep=','
 4 s=sep.join(li)
 5 print(s)    #使用逗号作为连接符
 6 s1=':'.join(li) #使用冒号作为连接符
 7 print(s1)
 8 s2=''.join(li)
 9 print(s2)
10 #使用split()和join()方法可以删除字符串中多余的空白字符,如果有连续多个空白字符,只保留一个
11 x='aaa          bb      c d e fff'
12 print(' '.join(x.split()))
13 
14 def equalilent(s1,s2):  #判断两个字符串在python意义上是否等价
15     if s1 == s2:
16         return True
17     elif ' '.join(s1.split()) == ' '.join(s2.split()):
18         return True
19     elif ''.join(s1.split()) == ''.join(s2.split()):
20         return True
21     else:
22         return False
23 print(equalilent('pip list','pip    list'))
24 # True
25 print(equalilent('[1,2,3]','[1,2,3]'))  #判断两个列表写法是否等价
26 # True
27 print(equalilent('[1,2,3]','[1,2,   3]'))
28 # True
29 print(equalilent('[1,2,3','[1,2 ,3,4]'))
30 # False
31 '''使用运算符"+"也可以连接字符串,但该运算符设计大量数据的复制,效率非常低,不适合大量长字符串的连接。'''
32 
33 import timeit
34 
35 #使用列表推导式生成10000个字符串
36 strlist = ['This is a long string that will not keep in memory.' for n in range(10000)]
37 
38 #使用字符串对象的join()方法连接多个字符串
39 def use_join():
40     return ''.join(strlist)
41 
42 #使用运算符"+"连接多个字符串
43 def use_plus():
44     result=''
45     for strtemp in strlist:
46         result = result+strtemp
47     return result
48 
49 if __name__=='__main__':
50     #重复运行次数
51     times=1000
52     jointimer = timeit.Timer('use_join()','from __main__ import use_join')
53     print('time for join:',jointimer.timeit(number=times))
54     # time for join: 0.1647309590189252
55     plustimer = timeit.Timer('use_plus()','from __main__ import use_plus')
56     print('time for plus:',plustimer.timeit(number=times))
57     # time for plus: 2.045372327003861
原文地址:https://www.cnblogs.com/cmnz/p/6953752.html