[Python-ideas] Create a StringBuilder class and use it everywhere

Nick Coghlan ncoghlan at gmail.com
Thu Aug 25 13:47:05 CEST 2011


If the join idiom really bothers you...

import io

def build_str(iterable):
    # Essentially ''.join, just with str() coercion
    # and less memory fragmentation
    target = io.StringIO()
    for item in iterable:
        target.write(str(item))
    return target.getvalue()

# Caution: decorator abuse ahead
# I'd prefer this to a StringBuilder class, though :)
def gen_str(g):
    return build_str(g())

>>> @gen_str
... def example():
...     yield 0
...     for i in range(1, 10):
...         yield ','
...         yield i
...
>>> print(example)
0,1,2,3,4,5,6,7,8,9

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list