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

Terry Reedy tjreedy at udel.edu
Thu Aug 25 17:24:40 CEST 2011


On 8/25/2011 5:28 AM, k_bx wrote:

>      class StringBuilder(object):
>          """Use it instead of doing += for building unicode strings from pieces"""
>          def __init__(self, val=u""):
>              self.val = val
>              self.appended = []
>
>          def __iadd__(self, other):
>              self.appended.append(other)
>              return self
>
>          def __unicode__(self):
>              self.val = u"".join((self.val, u"".join(self.appended)))
>              self.appended = []
>              return self.val

I do not see the need to keep the initial piece separate and do the 
double join. For Py3

class StringBuilder(object):
   """Use it instead of doing += for building unicode strings from pieces"""
   def __init__(self, val=""):
       self.pieces = [val]

   def __iadd__(self, item):
       self.pieces.append(item)
       return self

   def __str__(self):
       val = "".join(self.pieces)
       self.pieces = [val]
       return val

s = StringBuilder('a')
s += 'b'
s += 'c'
print(s)
s += 'd'
print(s)
 >>>
abc
abcd

I am personally happy enough with [].append, but I can see the 
attraction of += if doing many separate lines rather than .append within 
a loop.

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list