
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the most efficient string concatenation method in python?
String concatenation is the process of joining two or more strings together. It is important to choose the right method for string concatenation when dealing with building output, logging messages, etc.
While Python has several methods to concatenate strings, not all the methods perform equally, especially incase of nested loops. In this article, we will explore the different methods of string concatenation in Python.
Using Python + Operator
The first approach is by using the + operator, which is the straightforward way to concatenate strings. This method is inefficient in loops because it creates a new string object each time the '+' operator is used.
Example
Let's look at the following example, where we are going to use the simple and straightforward way for string concatenation.
str1 = "Welcome To, " + "TP." print(str1)
The output of the above program is as follows -
Welcome To, TP.
Using Python str.join() Method
The Python str.join() Method takes all the elements in an iterable(such as lists, strings, etc) separated by the given separator and joins them into one string.
It is the most efficient way to concatenate multiple strings. It avoids the repeated memory allocation by joining all the parts at once. Following is the syntax of the Python str.join() method -
str.join(sequence)
Example
Consider the following example, where we are going to use the str.join() method and concatenate the string.
str1 = ["Cars:", "Ciaz,", "Buggati", "and", "Audi"] result = " ".join(str1) print(result)
The output of the above program is as follows -
Cars: Ciaz, Buggati and Audi