How do you concatenate strings in Python?
Short answer: use the + operator to join two or three strings, an f-string when you mix text with variables or numbers, and join() when you have a list of strings:
name = "Ana"
age = 30
print("Hello, " + name) # Hello, Ana
print(f"{name} is {age} years old") # Ana is 30 years old
print(" ".join(["Learn", "Python"])) # Learn Python+ only joins text: to add a number, convert it with str() or use an f-string.
The + operator only joins text. f-strings convert numbers for you, and join() combines a whole list with the separator you choose.
Ways to concatenate strings in Python
| Method | Example | Use it to |
|---|---|---|
+ | "Hello, " + name | Join a few strings |
+= | text += "!" | Add text to a variable |
| f-string | f"{name} is {age} years old" | Mix text, variables and numbers |
join() | " ".join(words) | Join a list with a separator |
format() | "{} is {} years old".format(name, age) | Older code or reusable templates |
% | "%s is %d years old" % (name, age) | Read very old code |
* | "-" * 20 | Repeat a string |
Concatenate with the + operator
name = "Alex"
print("My name is " + name + " and I'm a developer")
# My name is Alex and I'm a developer+ does not add spaces. If you forget the space after is, you get My name isAlex.
Add text with +=
greeting = "Hello"
greeting += ", world"
print(greeting) # Hello, worldPython strings cannot be changed: += creates a new string and stores it in the same variable.
Concatenate with f-strings
Put an f before the quotes and write the variables inside curly braces. You can also do math and formatting inside the braces:
product = "Keyboard"
price = 20
print(f"{product}: ${price * 1.08:.2f} with tax")
# Keyboard: $21.60 with taxf-strings convert numbers to text for you and are the most readable option in modern Python.
Join a list with join()
words = ["Learn", "to", "code"]
print(" ".join(words)) # Learn to code
print("-".join(words)) # Learn-to-code
print("\n".join(words)) # one word per lineThe string before .join() is the separator. join() only accepts text: if the list has numbers, convert them first with map(str, items):
print(", ".join(map(str, [1, 2, 3]))) # 1, 2, 3To learn more, see how to convert a list to a string in Python.
Concatenate numbers and text
age = 30
print("You are " + str(age) + " years old") # You are 30 years old
print(f"You are {age} years old") # You are 30 years oldWithout str(), "You are " + age raises TypeError: can only concatenate str (not "int") to str.
format(), % and *
name = "Ana"
age = 30
print("{} is {} years old".format(name, age)) # Ana is 30 years old
print("%s is %d years old" % (name, age)) # Ana is 30 years old
print("ha" * 3) # hahahaformat() and % still work, but in new code an f-string reads better. * repeats a string as many times as you ask.
