try:
from StringIO import StringIO
except ImportError:
from io import StringIO
mylist = ['abcd' for i in range(5)]
file_str = StringIO()
for i in range(len(mylist)):
file_str.write(mylist[i])
print(file_str.getvalue())
"""
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)