Monday, January 24, 2011

String Concatenation in Python

Build a list of strings, then join it


def method():
str_list = []
for num in xrange(loop_count):
str_list.append(`num`)
return ''.join(str_list)

This approach is commonly suggested as a very pythonic way to do string concatenation. First a list is built containing each of the component strings, then in a single join operation a string is constructed conatining all of the list elements appended together.



Write to a pseudo file


from cStringIO import StringIO
import timing, commands, os
from sys import argv
def method():
from cStringIO import StringIO
file_str = StringIO()
for num in xrange(loop_count):
file_str.write(`num`)

The cStringIO module provides a class called StringIO that works like a file,
but is stored as a string. Obviously it's easy to append to a file - you simply
write at the end of it and the same is true for this module. There is a similar
module called just StringIO, but that's implemented in python whereas cStringIO
is in C. It should be pretty speedy. Using this object we can build our string
one write at a time and then collect the result using the getvalue() call.

return file_str.getvalue()

No comments: