How Can We Help?
Introduction
String builder is a popular concept in the programming languages like Java and C++. The StringBuilder is a collection of strings to form a larger string(lines).
However, python does not have a direct implementation of string builders. In fact, we can declare any string builder in python without even explicitly mentioning whether it is a string or any string builder.
There are also significant differences between the string and string builders.
- Strings are collections of characters, but the string builders are a collection of strings.
- The string is an immutable data type, but the string builders are mutable data types.
- Since the strings are immutable, each time we change their value, a new fresh memory is allocated to it. As the StringBuilder is mutable, if we wish to change its value, a new memory is allocated rather than the value being overwritten in the existent memory.
StringBuilders In Java
Before we move on to the python implementation of string builders, it will be a good idea to glimpse how the string builders are made in languages like Java.
Example (1)
public class index {
public static void main(String[] args) {
StringBuilder str = new StringBuilder("Hello world!");
System.out.println(str.toString());
StringBuilder rev = str.reverse();
System.out.println(rev.toString());
int capacity = str.capacity();
System.out.println(capacity);
}
}
Output:
Hello world!
!dlrow olleH
28
Now let us understand how to create string builders in python.
Using The Join Function
This is the most popular method to implement StringBuilder in python. This is an in-built function of python.
Syntax:
<string name>.join(<any iterable object/variable>)
Parameters:
Any form of iterable object/variable.
Return value:
A string object is the combination of the two tables.
Example (2)
string_list = ["Linux","MAC","Windows"]
str_join= ">"
print(str_join.join(string_list))
Output:
Linux>MAC>Windows
Explanation:
First, we created a list of strings and named the variable string_list. Next, we created another string named str_join.
Next, we used the join method. The join method iterated through the list named string_list and joins the sting str_join between every successive element of the list.
Since the StringBuilder is popular among object-oriented programming languages and in the programming languages like Java, this is a class-based implementation. We implement our previous code in the class-based method below:
Example (3)
# Define a user-defined class named StringBuilder
class StringBuilder:
# Building the constructor
def __init__(self, string_list, string_join):
# Performing the variable instantiation
self.string_list = string_list
self.string_join = string_join
# Creating a user-defined function
def builder(self):
# Returning the joined string
return self.string_join.join(self.string_list)
# Defining the main function
def main():
# Creating the object
Builders = StringBuilder(["Linux", "MAC", "Windows"], ">")
# Printing the return value
print(Builders.builder())
# Calling the main function
if __name__ == "__main__":
main()
Output:
Linux>MAC>Windows
String Concatatnation
String concatenation is a general operation that is performed on strings. This is performed with the help of the “+” operator of python. Other programming languages like Java, javascript, c++ also support similar operations.
We can also add multiple strings with the help of the “+” operator of python.
Example (4)
str_first ="Hello this is the first line."
str_second= "HELLO THIS IS THE SECOND LINE."
print(str_first+str_second)
Output:
Hello this is the first line.HELLO THIS IS THE SECOND LINE.
Class-based implementation of the above approach:
# Define a user-defined class named StringBuilder
class StringBuilder:
# Building the constructor
def __init__(self, str_first, str_second):
# Performing the variable instantiation
self.str_first = str_first
self.str_second = str_second
# Creating a user-defined function
def builder(self):
# Returning the joined string
return self.str_first+self.str_second
# Defining the main function
def main():
# Creating the object
Builders = StringBuilder(
"Hello this is the first line.", "HELLO THIS IS THE SECOND LINE.")
# Printing the return value
print(Builders.builder())
# Calling the main function
if __name__ == "__main__":
main()
Output:
Hello this is the first line.HELLO THIS IS THE SECOND LINE.
Unary Operation
We can also utilize the unary “+” operation of python to perform the concatenation and hence the string builder operation in python. This is similar to the previous method we discussed.
Example (5)
str_first ="Hello this is the first line."
str_first+= "HELLO THIS IS THE SECOND LINE."
print(str_first)
Output:
Hello this is the first line.HELLO THIS IS THE SECOND LINE.
Class-based implementation of the above approach:
# Define a user-defined class named StringBuilder
class StringBuilder:
# Building the constructor
def __init__(self, str_first, str_second):
# Performing the variable instantiation
self.str_first = str_first
self.str_second = str_second
# Creating a user-defined function
def builder(self):
# Performing the concatenation
self.str_first += self.str_second
# Returning the joined string
return self.str_first
# Defining the main function
def main():
# Creating the object
Builders = StringBuilder(
"Hello this is the first line.", "HELLO THIS IS THE SECOND LINE.")
# Printing the return value
print(Builders.builder())
# Calling the main function
if __name__ == "__main__":
main()
Output:
Hello this is the first line.HELLO THIS IS THE SECOND LINE.
Using the StringIO Module of Python
Python also allows us to create string builders using the StringIO module. For performing the string building using the StringIO module, we need to follow the following steps:
First, import the StringIO module. Next, define the string and create an object with the help of the StringIO module. We create a list consisting of the strings which we need to join. We iterate through the list and write into the StringIO object we created using the write function. Ultimately we get the value through the getValue function of python.
Example (6)
# Import the module
from io import StringIO
# Creating an object
string_build = StringIO()
# Define a list of string
str_list = ["First line."," Second line."," Third line."]
# Iterating through the list to write into the object
for i in str_list:
string_build.write(i)
# Printing the final string
print(string_build.getvalue())
Output:
First line. Second line. Third line.
Class-based implementation of the StringIO module:
Example (7)
# Import the module
from io import StringIO
# Define a user-defined class named StringBuilder
class StringBuilder:
# Building the constructor
def __init__(self, str_build, str_second):
# Performing the variable instantiation
self.str_build = str_build
self.str_second = str_second
# Creating a user-defined function
def builder(self):
for i in self.str_second:
self.str_build.write(i)
return self.str_build.getvalue()
# Defining the main function
def main():
# Creating an object
string_build = StringIO()
# Define a list of string
str_list = ["First line.", " Second line.", " Third line."]
# Creating the object
Builders = StringBuilder(string_build, str_list)
# Printing the return value
print(Builders.builder())
# Calling the main function
if __name__ == "__main__":
main()
Output:
First line. Second line. Third line.
How Is The StringBuilder of Python Different From The StringBuilder of Java?
There are many differences between the StringBuilder of Java and the StringBuilder of python. The most crucial difference is that while in Java, there is a direct in-built implementation of the StringBuilder, in python, there is no in-built direct implementation of the StringBuilder. We need to use the available functions of python to create a similar implementation.
Final Words
In this article, we understood how to create string builders in python using different methods. We used the functions and methods available in python for the equivalent StringBuilder operations. We also saw how to implement the same using the StringIO methods available in python. For all the methods, we also saw the equivalent class-based implementation.
We recommend that the readers practice the concepts by trying different methods and using the combined methods discussed.