Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python String Join: Syntax and Examples

Learn how to use Python's string join() method to concatenate iterables into a single string, with syntax, examples, and common mistakes to avoid.

~4 min readPython
#Python#string concatenation#join method#iterables
Illustration of Python string join method combining list elements with a separator into a single string

Python's str.join() method is the standard way to concatenate an iterable of strings into one string with a separator. You call the method on the separator string and pass the iterable as the argument. For example, ', '.join(['a', 'b', 'c']) returns 'a, b, c'. This is useful for formatting output, building log lines, and generating structured text.

How join() Works

The join() method is defined on the string type, not on the iterable. This means you call it on the separator, not on the list or tuple you want to combine. The syntax is separator.join(iterable), where iterable can be any object that yields strings when iterated over. The method returns a new string containing the elements of the iterable separated by the separator. If the iterable is empty, join() returns an empty string.

python
separator = "-" words = ["hello", "world"] result = separator.join(words) print(result) # hello-world

The separator can be any string, including an empty string. Using an empty separator concatenates the elements directly without any delimiter.

Joining Lists, Tuples, and Sets

Lists are the most common iterable passed to join(), but tuples and sets also work. The order of elements in a set is not guaranteed, so if order matters, use a list or tuple.

python
# List colors = ["red", "green", "blue"] print(", ".join(colors)) # red, green, blue # Tuple coordinates = ("40.7128", "74.0060") print(", ".join(coordinates)) # 40.7128, 74.0060 # Set (order not guaranteed) unique_ids = {"a1", "b2", "c3"} print("|".join(unique_ids)) # e.g., b2|c3|a1

When working with sets, remember that the output order is arbitrary. If you need a consistent order, sort the set first or use a list.

Joining Generators and Other Iterables

join() works with any iterable, including generators, map objects, and custom iterators. This is useful when you want to avoid writing a separate loop to collect strings first. For example, you can join the results of a generator expression directly.

python
numbers = [1, 2, 3, 4] result = ", ".join(str(n * 2) for n in numbers) print(result) # 2, 4, 6, 8

join() consumes the generator while building the result, so the generator cannot be reused afterward. If you need to reuse the values, keep them in a list first.

Similarly, map() can convert values before joining:

python
result = ", ".join(map(str, numbers)) print(result) # 1, 2, 3, 4

Common Mistakes and Edge Cases

One frequent error is trying to join non-string elements. join() expects every item in the iterable to be a string; otherwise, it raises a TypeError. Convert each element to a string explicitly, as shown in the generator example above.

Another edge case is joining an empty iterable. The method returns an empty string without raising an error, which is often the desired behavior.

python
empty_list = [] print(", ".join(empty_list)) # (blank)

If the iterable contains None or other non-string values, you need to handle them. For example, you might use a conditional expression to replace None with a placeholder.

python
values = ["apple", None, "banana"] result = ", ".join(v if v is not None else "N/A" for v in values) print(result) # apple, N/A, banana

Performance Considerations

join() is usually more efficient than concatenating strings in a loop. Strings are immutable in Python, so repeated concatenation can create many intermediate string objects. Because join() can allocate the final string in one step, it avoids most of those intermediate copies.

python
# Repeated concatenation: creates intermediate strings result = "" for i, word in enumerate(words): result += ("" if i == 0 else " ") + word # More efficient: join with a separator result = " ".join(words)

For small numbers of strings, the difference is negligible, but for large collections, join() is the recommended approach. This matters when building strings in a loop, such as constructing CSV rows or HTTP response bodies.

When Not to Use join()

join() is the right tool when you already have an iterable of strings and a fixed separator. If you are collecting pieces in a loop, append them to a list and call join() once after the loop; repeated += is usually unnecessary.

If you only need to combine a few known strings, ordinary concatenation or an f-string may be clearer. You also do not need join() to append a single character to one string. For example, path.rstrip('/') + '/' is clearer than '/'.join([path.rstrip('/'), '']).

If you need to format complex data structures with different separators or conditional logic, f-strings or the format() method may be more appropriate. join() is specifically for joining a flat iterable of strings with a fixed separator.

Working with Separators and Formatting

The separator can be any string, including newlines, tabs, or multi-character strings. This makes join() useful for generating structured text.

python
lines = ["Name: Alice", "Age: 30", "City: New York"] print("\n".join(lines)) # Name: Alice # Age: 30 # City: New York

You can also use join() to build CSV-like output by combining rows with commas and newlines. Joining a list of lists requires a generator expression or list comprehension.

python
rows = [["Alice", "30"], ["Bob", "25"]] csv = "\n".join(",".join(row) for row in rows) print(csv) # Alice,30 # Bob,25

This pattern is concise and avoids manual string building. join() does not add a trailing delimiter automatically, so append one explicitly if needed.

Compatibility: Text and Binary Data

str.join() is available in Python 3. Text strings are Unicode by default, so str.join() handles Unicode characters directly. For text strings, every item and the separator must be str; if any element is not a string, join() raises TypeError. For binary data, use b''.join() with bytes elements.

python
data = [b'hello', b'world'] result = b' '.join(data) print(result) # b'hello world'

Understanding these details helps avoid errors when working with text and binary data.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.