Skip to content

Instantly share code, notes, and snippets.

@buildwithmh
Last active January 1, 2021 16:04
Show Gist options
  • Save buildwithmh/d7cee6a9aeaf01e0d7915eb44f7d8e6d to your computer and use it in GitHub Desktop.
Save buildwithmh/d7cee6a9aeaf01e0d7915eb44f7d8e6d to your computer and use it in GitHub Desktop.
String Builder in python
class StringBuilder(object):
def __init__(self, val):
self.store = [val]
def __iadd__(self, value):
self.store.append(value)
return self
def __str__(self):
return "".join(self.store)
#Test
initial = 'value'
stringBuilder = StringBuilder(initial)
for _ in range(2000):
stringBuilder += 'value'
print(str(stringBuilder))
#Thanks to
#https://grokbase.com/t/python/python-ideas/118sgkcgg0/create-a-stringbuilder-class-and-use-it-everywhere
@droopy4u
Copy link

droopy4u commented Jan 1, 2021

Great, but is it possible to create some advanced features?
ex void Clear()

compared to, VS ... such as in
https://www.chilkatsoft.com/refdoc/pythonStringBuilderRef.html

  • void Clear()
  • bool Append(string value)
  • bool Contains(string str, bool caseSensitive)
initial = 'value'
stringBuilder = StringBuilder('')
print(" id {} - string {} \n str(): {} - repr(): {}".format( id(stringBuilder), stringBuilder, repr(stringBuilder), str(stringBuilder)))
stringBuilder +="test"
print(" id {} - string {}\n".format( id(stringBuilder), stringBuilder))
for _ in range(10):
    stringBuilder += 'value'
print(str(stringBuilder))

print(" id {} - string {}\n".format( id(stringBuilder), stringBuilder))
stringBuilder=''
print(" id {} - string {}\n".format( id(stringBuilder), stringBuilder))
      results in :
id 140226925842928 - string  
 str(): <__main__.StringBuilder object at 0x7f89201a51f0> - repr(): 
 id 140226925842928 - string test

testvaluevaluevaluevaluevaluevaluevaluevaluevaluevalue
 id 140226925842928 - string testvaluevaluevaluevaluevaluevaluevaluevaluevaluevalue

 id 140227461358320 - string

id 140226925842928 - string testvaluevaluevaluevaluevaluevaluevaluevaluevaluevalue
VS
id 140227461358320 - string

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment