The fastest way of join string in Python

Asked By 7060 points N/A Posted on -
qa-featured

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 " "

SHARE
Answered By 0 points N/A #84118

The fastest way of join string in Python

qa-featured

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)])

Related Questions