Python - String Concatenation
String concatenation in Python means joining two or more strings into one. It’s a fundamental skill you'll use frequently when working with text, output formatting, or user input.
This tutorial explains all the ways you can concatenate strings in Python — with examples, best practices, and useful tips.
What is String Concatenation?
Concatenation simply means adding strings together.
Example:
a = "Hello"
b = "World"
print(a + b) # Output: HelloWorld
To include a space, manually add it:
print(a + " " + b) # Output: Hello World
Methods to Concatenate Strings
Python offers several ways to concatenate strings:
➕ 1. Using the +
Operator (Most Common)
first = "Python"
second = "Rocks"
result = first + " " + second
print(result) # Output: Python Rocks
✅ Use this for quick and simple joins.
2. Using +=
Operator (Appending Strings)
greeting = "Hello"
greeting += " "
greeting += "there!"
print(greeting) # Output: Hello there!
3. Using join()
(Best for Joining Lists)
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # Output: Python is awesome
✅ Best practice when concatenating multiple strings (like in a loop).
4. Using f-strings
(Formatted String Literals)
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 25 years old.
✅ Recommended in Python 3.6+ for readability and performance.
5. Using format()
Method
language = "Python"
version = 3
print("You are using {} version {}".format(language, version))
# Output: You are using Python version 3
Common Mistake: Mixing Strings with Numbers
You cannot concatenate a string with an integer directly:
age = 25
# print("Age: " + age) ❌ TypeError
✅ Correct way:
print("Age: " + str(age)) # Using str()
print(f"Age: {age}") # Using f-string
Real-World Example
Example: Greeting a User
first_name = "John"
last_name = "Doe"
greeting = "Hello, " + first_name + " " + last_name + "!"
print(greeting) # Output: Hello, John Doe!
Summary Table
Method | Syntax/Example | Use Case |
---|---|---|
+ operator | "Hello" + " " + "World" | Quick joins |
+= operator | txt += " more" | Appending |
join() | " ".join(["Python", "is", "great"]) | Best for joining lists |
f-strings | f"My name is {name}" | Python 3.6+, preferred method |
format() | "Hello, {}".format(name) | Pre-3.6 compatibility |