Strings in python are immutable, and the speed will be slow when splicing, because splicing any immutable sequence will generate a new sequence object
In other words, a lot of intermediate objects will be generated during the splicing process. It will definitely take time to create new objects, and this obviously wastes memory
The optimized way is to use .join() instead
The experiment code is as follows:
import time
import numpy as np
ls=['AA_'+str(i) for i in range(10000000)]
s=""
st=time.time()
for i in ls:
s+=i
print(time.time()-st)
#print(s)
s=""
st=time.time()
s=s.join(ls)
#print(s)
print(time.time()-st)
operation result:
0.9245333671569824
0.08815383911132812
From the results, it can be seen that the speed of direct splicing will be more than ten times slower, so you need to pay attention when splicing strings.