StringBuilder Python
# StringIO can be used to read/write strings from/to memory buffer.
# import StringIO
try:
from StringIO import StringIO # for Python 2
except ImportError:
from io import StringIO # for Python 3
mylist = ['abcd' for i in range(5)] # myList = [abcdabcdabcdabcdabcd]
file_str = StringIO() # create StringIO object
for i in range(len(mylist)):
file_str.write(mylist[i]) # write data to StringIO object
print(file_str.getvalue()) # abcdabcdabcdabcdabcd
"""
Alternatively, we can rely on the StringIO module
to create a class having same capabilities as
StringBuilder of other languages.
"""
class StringBuilder:
_file_str = None
def __init__(self):
self._file_str = StringIO()
def Append(self, str):
self._file_str.write(str)
def __str__(self):
return self._file_str.getvalue()
sb = StringBuilder()
sb.Append("Hello ")
sb.Append("World")
print(sb) # Hello World
Wissam