String Builder Equivalent in Python
In Python, strings are immutable, which means they cannot be edited in their existing memory block.
To get around this problem other programming languages such as C# have a StringBuilder class for efficiently creating mutable strings. Unfortunately, Python does not have this feature built-in, but we can get around this by concatenating strings ourselves, which is what we will be learning to do in this tutorial.
Build String in Python with join()
To build a mutable string from a list in Python, use the join()
function like this:
items = ['a','b','c','d']
string = "".join(items)
print(string)
abcd
Concatenate List to String with for Loop
Another way of building a string with dynamic memory allocation is to use the +=
operator inside a for loop like this:
items = ['a','b','c','d']
string = ''
for i in items:
string += i
print(string)
abcd
Build Strings with StringIO
It is also possible to write mutable strings to memory using the StringIO
class from the io
package. Using it would look something like this:
from io import StringIO
items = ['a','b','c','d']
file_str = StringIO()
for i in items:
file_str.write(i)
print(file_str.getvalue())
abcd