Home > python > StringBuilder functionality in Python

StringBuilder functionality in Python

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()
About these ads
  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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 65 other followers

%d bloggers like this: