String Builder in Python

Let’s start with Java language. Strings in Java, by default, are immutable – objects whose state cannot be modified after it is defined. The opposite of an immutable object is mutable.

Java programming languages natively support the StringBuilder class to support the mutability of Java strings.

Python Strings are also immutable. However, Python does not support StringBuilder natively, but we can use some equivalent methods to make a custom string builder.

This article will discuss the following methods:

  • Method 1: Using <str>.join(iterable),
  • Method 2: String concatenation using “+” operator, and,
  • Method 3: Using StringIO() class in io module

Method 1: Using <str>.join(iterable)

The <str>.join(iterable) is used to join elements of the iterable on <str>. Here is an example.

Output:

Apples Bananas Oranges Grapes

Note that the elements of the iterable being joined must be of string type; otherwise TypeError exception like this will be raised.

TypeError: sequence item <index>: expected str instance, <non_int_type> found

Therefore, if you have an iterable with mixed datatype, you need to change them to strings. For example,

Output:

Apples#55#None#Grapes

In the above example, map(<func>, iterable) applies the function, <func>, to each item in the iterable.

Method 2: Concatenating Multiple Strings

You can also build a custom string on Python using the “+” operator to concatenate multiple strings into 1.

If you have a few strings to merge, you can use something like this.

Output:

Thisisawesome

However, a for-loop can suffice if you have a long list of strings you want to join.

Output:

Apples Bananas Oranges Grapes Berries

Method 3: Using StringIO() Class on io Module

The following example shows how to use this class to join strings. The code contains comments to help you understand the lines.

Output:

This is awesome

Conclusion

Python does not natively support StringBuilder; however, you can create custom builders using the three methods discussed in this article. The first method is a method commonly used to join strings in Python.