Home > python > StringBuilder functionality in Python

StringBuilder functionality in Python


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


def g():
    sb = []
    for i in range(30):

    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()
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: