split() split and join() merge

split() can split a string into multiple substrings (stored in a list) based on the specified separator. If no delimiter is specified, blank characters (newline/space/tab) are used by default

>>> a= "to be or not to be"
>>> a.split()
['to', 'be', 'or', 'not', 'to', 'be']
>>> a.split("be")
['to ', ' or not to ', '']

The usage of join() is just the opposite, mainly used for string splicing`

>>> a= ["python",'java',"VB"]
>>> "*".join(a)
'python*java*VB'

Using the string splicing symbol + will form a new string object, so it is not recommended to use + to splice strings. It is recommended to use the join function, because the join function calculates the length of all strings before splicing the strings, and then copies them one by one. Create a new object only once

'''测试运行时间'''
a= ""
import time

time1= time.time()
for i in range(10000000):
    a= a+"str"
time2= time.time()

print("所用时间1:"+ str(time2-time1))



time3= time.time()
b = []
for i in range(10000000):
    b.append("str")
a="".join(b)
time4= time.time()
print("所用时间2:"+ str(time4-time3))

Guess you like

Origin blog.csdn.net/yue008/article/details/108697266