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
Add one Python string to another
String concatenation in Python combines two or more strings into a single string. Python provides several methods to add strings together, with the + operator and join() method being the most common approaches.
Using the + Operator
The + operator concatenates strings by combining them sequentially. This is the most straightforward method for joining strings ?
first_string = "What a beautiful "
second_string = "flower"
print("Given string s1:", first_string)
print("Given string s2:", second_string)
# Using + operator
result = first_string + second_string
print("Result after adding strings:", result)
Given string s1: What a beautiful Given string s2: flower Result after adding strings: What a beautiful flower
Adding Numeric Strings
When working with numeric strings, the + operator performs concatenation, not arithmetic addition ?
num_str1 = '54'
num_str2 = '02'
print("Given string s1:", num_str1)
print("Given string s2:", num_str2)
result = num_str1 + num_str2
print("Result after adding numeric strings:", result)
Given string s1: 54 Given string s2: 02 Result after adding numeric strings: 5402
Using the join() Method
The join() method is more efficient for concatenating multiple strings. It takes an iterable of strings and joins them with a specified separator ?
first_string = "What a beautiful "
second_string = "flower"
print("Given string s1:", first_string)
print("Given string s2:", second_string)
# Using join() with empty separator
result = "".join([first_string, second_string])
print("Result using join():", result)
Given string s1: What a beautiful Given string s2: flower Result using join(): What a beautiful flower
Join() with Multiple Strings
The join() method is particularly useful when concatenating many strings ?
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print("Joined sentence:", sentence)
# Join without separator
numbers = ['1', '2', '3', '4']
combined = "".join(numbers)
print("Combined numbers:", combined)
Joined sentence: Python is awesome Combined numbers: 1234
Comparison
| Method | Best For | Performance | Readability |
|---|---|---|---|
| + operator | 2-3 strings | Good for few strings | Very readable |
| join() method | Multiple strings | Better for many strings | More complex syntax |
Conclusion
Use the + operator for simple concatenation of 2-3 strings. For joining multiple strings or when performance matters, use the join() method as it's more memory efficient.
