
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
How to join two strings to convert to a single string in Python?
In Python, we can join two strings into one single string using different ways, such as -
- Using the + Operator
- Using the join() Method
- Using Formatted Strings
- String Concatenation in Loops
Let us look at each method with examples.
Using + Operator
The most common way to combine two strings into one in Python is by using the + operator. It joins the strings exactly as they are, without any space or separator in between.
Example
In the following example, we are joining two strings using the + operator -
str1 = "Hello" str2 = "World" result = str1 + " " + str2 print(result)
Following is the output obtained -
Hello World
Using the join() Method
The join() method is used when we need to combine multiple strings with a separator. Even for two strings, you can place them in a list or tuple and use join() method to merge them with or without a separator.
Example
In the following example, we are joining two strings with a space in between using ' '.join() method -
str1 = "Hello" str2 = "World" result = " ".join([str1, str2]) print(result)
We get the output as shown below -
Hello World
Using f-strings
Formatted string literals, or f-strings, are used to insert variables directly into a string using curly braces. To combine two strings, we need to use the string format string f"{str1} {str2}" -
Example
In the following example, we combine two strings using an f-string -
str1 = "Hello" str2 = "World" result = f"{str1} {str2}" print(result)
The output obtained is as shown below -
Hello World
Using "%" Formatting
In Python string formatting, placeholders like %s are used inside the string and replaced by values. To combine two strings, we just need to use two string place holders and print them as one.
Example
In the following example, we use %s to format and join two strings -
str1 = "Hello" str2 = "World" result = "%s %s" % (str1, str2) print(result)
The result produced is as follows -
Hello World
Using format() Method
The format() method is also used to insert values into a string using curly braces {}. To combine two strings, we need to invoke the format() method on the string "{} {}", by passing the desired strings as parameters.
Example
In the following example, we use the format() method to merge two strings.
str1 = "Hello" str2 = "World" result = "{} {}".format(str1, str2) print(result)
Following is the output obtained -
Hello World