How do I append one string to another in Python?
Categories:
Mastering String Concatenation in Python

Learn the various methods to append and combine strings in Python, from simple concatenation to efficient formatting techniques, and understand their performance implications.
String concatenation is a fundamental operation in programming, allowing you to combine two or more strings into a single, longer string. Python offers several intuitive and efficient ways to achieve this, each with its own use cases and performance characteristics. This article will guide you through the most common methods, helping you choose the best approach for your specific needs.
The '+' Operator: Simple Concatenation
The most straightforward way to append strings in Python is by using the +
operator. This operator creates a new string by joining the operands. It's highly readable and suitable for concatenating a small number of strings.
string1 = "Hello"
string2 = "World"
result = string1 + " " + string2
print(result) # Output: Hello World
# Concatenating multiple strings
name = "Alice"
age = 30
greeting = "My name is " + name + " and I am " + str(age) + " years old."
print(greeting) # Output: My name is Alice and I am 30 years old.
Using the +
operator for basic string concatenation.
+
operator can only concatenate strings with other strings. If you try to concatenate a string with a non-string type (like an integer), Python will raise a TypeError
. Always convert non-string types to strings using str()
before concatenating.The .join()
Method: Efficient Concatenation for Iterables
When you need to concatenate a large number of strings, especially those stored in a list or other iterable, the str.join()
method is the most efficient and Pythonic approach. It takes an iterable of strings as an argument and joins them together using the string on which the method is called as a separator.
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # Output: Python is awesome
# Joining with a different separator
items = ["apple", "banana", "cherry"]
comma_separated = ", ".join(items)
print(comma_separated) # Output: apple, banana, cherry
# Joining an empty list
empty_list = []
empty_string = "-".join(empty_list)
print(f"Empty join: '{empty_string}'") # Output: Empty join: ''
Using the .join()
method for efficient string concatenation from a list.
.join()
method is significantly more efficient than using the +
operator in a loop for many strings. This is because +
creates a new string object in memory for each concatenation, leading to multiple intermediate string objects, while .join()
calculates the final string size once and builds it directly.f-Strings (Formatted String Literals): Modern and Readable
Introduced in Python 3.6, f-strings provide a concise and readable way to embed expressions inside string literals. They are prefixed with f
or F
and allow you to place variables or expressions directly within curly braces {}
inside the string. This is often the preferred method for string formatting and concatenation when readability is key.
name = "Charlie"
age = 25
city = "New York"
# Basic f-string usage
message = f"My name is {name} and I am {age} years old."
print(message) # Output: My name is Charlie and I am 25 years old.
# Embedding expressions
price = 19.99
quantity = 3
total = f"The total cost is ${price * quantity:.2f}."
print(total) # Output: The total cost is $59.97.
# Multi-line f-strings
long_message = f"""Hello {name},
Welcome to {city}.
We hope you enjoy your stay!"""
print(long_message)
Using f-strings for clear and concise string concatenation and formatting.
The %
Operator (Old Style Formatting) and .format()
Method
While f-strings are generally recommended for new code, you might encounter older codebases using the %
operator or the .format()
method. These are still valid ways to concatenate and format strings.
# Using the % operator (old style formatting)
item = "book"
price = 15.50
old_format = "The %s costs $%.2f." % (item, price)
print(old_format) # Output: The book costs $15.50.
# Using the .format() method
product = "laptop"
quantity = 2
new_format = "You bought {} {}s.".format(quantity, product)
print(new_format) # Output: You bought 2 laptops.
# Using named arguments with .format()
named_format = "Hello {name}, your balance is ${balance:.2f}.".format(name="David", balance=1234.567)
print(named_format) # Output: Hello David, your balance is $1234.57.
Examples of string formatting using the %
operator and .format()
method.
%
operator is considered legacy and can be less readable and more error-prone than .format()
or f-strings, especially with many arguments or complex formatting. It's generally best to avoid it in new Python code.flowchart TD A[Start] A --> B{Number of Strings?} B -->|Few strings| C[Use '+' Operator] B -->|Many strings (from iterable)| D[Use '.join()' Method] B -->|Formatting & Variables| E[Use f-Strings] C --> F[End] D --> F[End] E --> F[End]
Decision flow for choosing a string concatenation method in Python.
Performance Considerations
While readability and maintainability are often paramount, understanding the performance implications of different concatenation methods can be crucial for performance-critical applications or when dealing with very large numbers of strings. The +
operator, when used repeatedly in a loop, can be inefficient due to the creation of many intermediate string objects. The .join()
method is generally the most performant for concatenating many strings from an iterable, as it optimizes memory allocation. f-strings and .format()
are also highly optimized for their use cases.
1. Choose the Right Tool
For 2-3 strings, the +
operator is fine. For many strings in a list, use .join()
. For embedding variables and expressions, use f-strings.
2. Ensure Type Consistency
Always convert non-string types to strings (e.g., using str()
) before concatenating them with string methods or operators, unless using f-strings which handle this automatically.
3. Prioritize Readability
While performance matters, especially for large-scale operations, always prioritize code readability and maintainability. f-strings often strike the best balance.