Is there anything in Python like Java\'s StringBuffer? Since strings are immutable in Python too, editing them in loops would be inefficient.
The previously provided answers are almost always best. However, sometimes the string is built up across many method calls and/or loops, so it's not necessarily natural to build up a list of lines and then join them. And since there's no guarantee you are using CPython, or that CPython's optimization will apply, an alternative approach is to just use print!
Here's an example helper class, although the helper class is trivial and probably unnecessary, it serves to illustrate the approach (Python 3):
import io
class StringBuilder(object):
def __init__(self):
self._stringio = io.StringIO()
def __str__(self):
return self._stringio.getvalue()
def append(self, *objects, sep=' ', end=''):
print(*objects, sep=sep, end=end, file=self._stringio)
sb = StringBuilder()
sb.append('a')
sb.append('b', end='\n')
sb.append('c', 'd', sep=',', end='\n')
print(sb) # 'ab\nc,d\n'