API Navigator Logo

How to Concatenate Strings in Python

Author: Newtum

This example covers several common and efficient methods for joining strings together in Python.

Using the `+` Operator

The simplest way to concatenate two or more strings is by using the `+` operator. This creates a new string containing the combined text.

str1 = "Hello"
str2 = "World"
result = str1 + ", " + str2 + "!"
print(result)

Using f-strings (Formatted String Literals)

F-strings (available in Python 3.6+) are a highly readable and efficient way to embed expressions inside string literals for formatting.

name = "Alice"
age = 30
greeting = f"My name is {name} and I am {age} years old."
print(greeting)

Using the `str.join()` Method

The `.join()` method is the most efficient way to concatenate a large number of strings from an iterable (like a list). You call it on the separator string you want between the elements.

words = ["Python", "is", "a", "powerful", "language"]

# Join the words with a space in between
sentence = " ".join(words)
print(sentence)

# Join with a different separator
csv_line = ",".join(words)
print(csv_line)