Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 approaches. Each method has its own advantages depending on the use case.
Using + Operator
The most common way to combine two strings is by using the + operator. It concatenates strings exactly as they are, without any automatic separator ?
str1 = "Hello"
str2 = "World"
# Direct concatenation without space
result1 = str1 + str2
print("Without space:", result1)
# Adding space manually
result2 = str1 + " " + str2
print("With space:", result2)
Without space: HelloWorld With space: Hello World
Using join() Method
The join() method is efficient when combining multiple strings with a separator. Place the strings in a list and specify the separator ?
str1 = "Hello"
str2 = "World"
# Join with space
result1 = " ".join([str1, str2])
print("With space:", result1)
# Join without separator
result2 = "".join([str1, str2])
print("Without separator:", result2)
# Join with custom separator
result3 = "-".join([str1, str2])
print("With dash:", result3)
With space: Hello World Without separator: HelloWorld With dash: Hello-World
Using f-strings (Recommended)
F-strings provide the most readable way to combine strings by embedding variables directly within curly braces ?
str1 = "Hello"
str2 = "World"
result = f"{str1} {str2}"
print(result)
# More complex formatting
name = "Alice"
age = 25
message = f"{str1} {str2}, I'm {name} and I'm {age} years old"
print(message)
Hello World Hello World, I'm Alice and I'm 25 years old
Using format() Method
The format() method uses curly braces as placeholders and is compatible with older Python versions ?
str1 = "Hello"
str2 = "World"
result = "{} {}".format(str1, str2)
print(result)
# With positional arguments
result2 = "{1} {0}".format(str1, str2)
print("Reversed order:", result2)
Hello World Reversed order: World Hello
Using % Formatting (Legacy)
The percent formatting uses %s placeholders and is mainly used for compatibility with older code ?
str1 = "Hello" str2 = "World" result = "%s %s" % (str1, str2) print(result)
Hello World
Performance Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
+ operator |
High | Good for 2-3 strings | Simple concatenation |
join() |
Medium | Best for many strings | Multiple strings with separator |
| f-strings | Very High | Fast | Modern Python (3.6+) |
format() |
High | Good | Complex formatting |
% formatting |
Low | Slower | Legacy code |
Conclusion
For modern Python development, use f-strings for their readability and performance. Use join() when combining many strings with separators, and the + operator for simple two-string concatenation.
