The fastest way of join string in Python
Dear expert kindly ask you to advise me the fastest way of string join in Python 2.7. I know two of such methods – using .join method and next one with symbol " "
Dear expert kindly ask you to advise me the fastest way of string join in Python 2.7. I know two of such methods – using .join method and next one with symbol " "
You should try the following methods to do the needful:
1: Â Â Â Â Â Â Â Naive appending
def method1(): out_str = '' for num in xrange(loop_count): out_str += `num` return out_str
I think it is the most noticeable loom to the difficulty. We can use here the concatenate operator (+=). loop_count gives the number of strings to be employed. Â
2: Â Â Â Â Â Â Â Mutable String class
def method2():
from UserString import MutableString
out_str = MutableString()
for num in xrange(loop_count):
out_str += `num`
return out_str
3: Â Â Â Â Â Â Â Character array
def method3():
from array import array
char_array = array('c')
for num in xrange(loop_count):
char_array. fromstring(`num`)
return char_array. tostring()
4: Â Â Â Â Â Â Â Make a list of strings
def method4():
str_list = []
for num in xrange(loop_count):
str_list. append(`num`)
return ''. join(str_list)
5: Â Â Â Â Â Â Â Write to a pseudo file
def method5():
from cStringIO import StringIO
file_str = StringIO()
for num in xrange(loop_count):
file_str. write(`num`)
return file_str. getvalue()
6: Â Â Â Â Â Â Â List comprehensions
def method6():
return ''. join([`num` for num in xrange(loop_count)])