Concatenate Strings
Concatenation Methods
Strings can be combined in different ways. The + operator works well for a few strings. The join() method is efficient when joining many strings from an iterable. f-strings (Python 3.6+) are ideal for combining variables with text.
Example
# Using + operator
full_name = "John" + " " + "Doe"
print(full_name) # John Doe
# Using join() for sequences
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # Python is awesome
# Using f-strings
name = "Alice"
greeting = f"Hello {name}!"
print(greeting) # Hello Alice!
Output
John Doe Python is awesome Hello Alice!
Performance Considerations
Some methods are more efficient than others depending on the situation. The + operator is fine for a few strings but inefficient in loops. The join() method is best for combining many strings. f-strings are both readable and efficient for embedding variables.
⚠️ Warning: Avoid using + repeatedly in loops, as it creates new strings each time and can hurt performance.
Method | Use Case | Performance |
---|---|---|
+ operator | Concatenating a small number of strings | Good |
join() | Combining many strings from a list or iterable | Best |
f-strings | Mixing variables with text | Excellent |
% formatting | Older codebases, legacy style | Fair |
format() | Complex formatting cases | Good |
Advanced Techniques
For very long strings, you can split them across multiple lines inside parentheses without using explicit operators. When constructing large strings incrementally (such as in a loop), using StringIO can be more memory-efficient.
Example
# Multi-line concatenation without +
long_text = (
"This is a very long string "
"that spans multiple lines "
"in the source code."
)
print(long_text)
# Using StringIO for incremental building
from io import StringIO
buffer = StringIO()
for word in ["Python", "is", "great"]:
buffer.write(word + " ")
result = buffer.getvalue().strip()
print(result)
Output
This is a very long string that spans multiple lines in the source code. Python is great