Posts Tagged ‘StringIO’
StringBuilder functionality in Python
September 27, 2010
Leave a comment
Problem
You need to concatenate lots of string elements. Under Java we use a StringBuilder for this, but how to do that in Python?
Solution #1
Use a list, and join the elements of the list at the end. This is much more efficient than concatenating strings since strings are immutable objects, thus if you concatenate a string with another, the result is a NEW string object (the problem is the same with Java strings).
Example:
def g(): sb = [] for i in range(30): sb.append("abcdefg"[i%7]) return ''.join(sb) print g() # abcdefgabcdefgabcdefgabcdefgab
Solution #2 (update 20120110)
Use a StringIO object and print to it. In short:
from cStringIO import StringIO out = StringIO() print >>out, 'arbitrary text' # 'out' behaves like a file return out.getvalue()
Categories: python
concatenate, java, string, stringbuffer, stringbuilder, StringIO