AppDividend
Latest Code Tutorials

Is There Any Concept Like String Builder in Python?

0

The string object in Python is immutable, which means every time a string is assigned to a variable, a new object is created in the memory to describe a new value. StringBuilder objects are like String objects, except that they can be modified. StringBuilder class in Java is also used to create mutable string objects.

Python String Builder

Is there some string class in Python like StringBuilder in Java? No, there is no built-in string builder in Python. There is no one-to-one correlation. There is a logical reason behind it. Building long strings in Python can sometimes result in prolonged running code.

Although in the latest versions of Python, there are ways you can build the strings. One common way to build large strings from pieces is to grow a list of strings and join it when you are done. This is a frequently-used Python idiom. To build strings combining data with formatting, you would do the formatting separately.

Create custom string builder in Python

To create a custom string builder, use one of the following methods.

  1. Using the string.join() method
  2. Using String concatenation
  3. Using StringIO Module

Using string.join() method

The string join() is a built-in Python method that returns the string concatenated with the elements of an iterable. To join strings from a list, we can use the join() function.

Example of String builder using join()

marvel = ['Loki' for i in range(7)]
studios = "".join(marvel)
print(studios)

Output

LokiLokiLokiLokiLokiLokiLoki

You can see that it prints the Loki seven times.

Using String Concatenation

To concatenate the strings from a list, use the combination of concatenating operator(+) and for loop.

Example of String builder using String Concatenation

marvel = ['Loki' for i in range(7)]
studios = ""

for i in range(len(marvel)):
    studios += marvel[i]
print(studios)

Output

LokiLokiLokiLokiLokiLokiLoki

Using StringIO Module

The StringIO is a built-in Python module that can read and write strings in the memory buffer. We create a StringIO object and write it to this object after looping through the list. Then we can print the required string using the getvalue() method.

Example of String builder using StringIO

To work with the StringIO module, you need to import it at the head of your file.

from io import StringIO

Now, create a StringBuilder class and define three methods of that class.

class StringBuilder:
    _file_str = None

    def __init__(self):
        self._file_str = StringIO()

    def Add(self, str):
        self._file_str.write(str)

    def __str__(self):
        return self._file_str.getvalue()

The Add() method append the strings pass to that function and the _str_() method returns the concatenated strings.

The last step is to call these functions by creating the class’s object.

string_builder = StringBuilder()

string_builder.Add("Snyder ")
string_builder.Add("Cut ")
string_builder.Add("2021")

print(string_builder)

See the following complete code.

from io import StringIO


class StringBuilder:
    _file_str = None

    def __init__(self):
        self._file_str = StringIO()

    def Add(self, str):
        self._file_str.write(str)

    def __str__(self):
        return self._file_str.getvalue()


string_builder = StringBuilder()

string_builder.Add("Snyder ")
string_builder.Add("Cut ")
string_builder.Add("2021")

print(string_builder)

Output

Snyder Cut 2021

And we got the strings concatenated as we expected.

That is it for Python String Builder Tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.