ZetCode

Python join string

last modified November 19, 2026 Python 3.15

In this article we show how to join strings in Python with the join method.

The str.join method concatenates the strings of an iterable and puts a separator between them. It is called on the separator, not on the list:

separator.join(iterable)

Joining is the opposite of splitting. This article covers the method itself. Converting numbers and other objects before joining is covered in Python list to string, and the comparison of join with the + operator in Python add string.

The join method

The simplest use joins a list of words with a space.

join_simple.py
words = ['an', 'old', 'silent', 'pond']

sentence = ' '.join(words)

print(sentence)
print(words)

The space string is the separator. The method returns a new string; the list is not modified. The separator goes only between the items, not after the last one.

$ python join_simple.py
an old silent pond
['an', 'old', 'silent', 'pond']

Separators

Any string can be a separator, including the empty string and strings of several characters.

separators.py
colours = ['red', 'green', 'blue']

print(''.join(colours))
print(','.join(colours))
print(', '.join(colours))
print(' | '.join(colours))
print('\n'.join(colours))
print(' -> '.join(colours))

The empty string glues the items together. The newline separator puts each item on its own line.

$ python separators.py
redgreenblue
red,green,blue
red, green, blue
red | green | blue
red
green
blue
red -> green -> blue

Joining any iterable

The argument of join does not have to be a list. Any iterable that yields strings works.

iterables.py
print(' '.join(('a', 'tuple', 'of', 'words')))
print('-'.join('abc'))

capitals = {'Slovakia': 'Bratislava', 'Hungary': 'Budapest'}
print(', '.join(capitals))
print(', '.join(capitals.values()))

tags = {'python', 'strings', 'join'}
print(', '.join(sorted(tags)))

print(' '.join(word.upper() for word in ['sky', 'blue']))

A string is an iterable of characters, so joining it puts the separator between the letters. Iterating a dictionary yields its keys; for the values we call values. A set has no defined order, so we sort it first to get a predictable result. The last line passes a generator expression; the extra parentheses are not needed when it is the only argument.

$ python iterables.py
a tuple of words
a-b-c
Slovakia, Hungary
Bratislava, Budapest
join, python, strings
SKY BLUE

Non-string items

The join method does not convert items to strings.

join_error.py
row = ['Alice', 34, 'Bratislava']

print(', '.join(row))

The second item is an integer and join raises a TypeError. The message names the index of the first bad item. The fix is to convert the items with str, map, or a formatting expression; see Python list to string.

$ python join_error.py
Traceback (most recent call last):
  File "/home/user/python/join_error.py", line 3, in <module>
    print(', '.join(row))
          ~~~~~~~~~^^^^^
TypeError: sequence item 1: expected str instance, int found

Split and join

Splitting on a separator and joining with the same separator gives back the original string. Splitting on whitespace does not.

split_join.py
csv_line = 'Bratislava,,Prague,Vienna'

fields = csv_line.split(',')
print(fields)
print(','.join(fields) == csv_line)

text = 'an  old\tpond'

words = text.split()
print(words)
print(' '.join(words) == text)
print(' '.join(words))

With an explicit separator, split keeps empty fields, so the round trip is exact. Without arguments, split treats any run of whitespace as one separator and the information about the original spacing is lost. This is useful when we want to normalize the spacing of a text.

$ python split_join.py
['Bratislava', '', 'Prague', 'Vienna']
True
['an', 'old', 'pond']
False
an old pond

Joining lines

When we join lines with '\n', the last line gets no newline. Text files usually end with one.

lines.py
from pathlib import Path

lines = ['first line', 'second line', 'third line']

Path('out1.txt').write_text('\n'.join(lines), encoding='utf-8')
Path('out2.txt').write_text('\n'.join(lines) + '\n', encoding='utf-8')

for name in ['out1.txt', 'out2.txt']:
    print(name, repr(Path(name).read_text(encoding='utf-8')))

text = 'one\ntwo\nthree\n'
parts = text.splitlines(keepends=True)
print(parts)
print(''.join(parts) == text)

The first file lacks the final newline; we add it ourselves in the second. Lines from splitlines(keepends=True) or from a file still contain their line endings, so we join them with the empty string.

$ python lines.py
out1.txt 'first line\nsecond line\nthird line'
out2.txt 'first line\nsecond line\nthird line\n'
['one\n', 'two\n', 'three\n']
True

Groups of characters

Card numbers and bank account numbers are easier to read in groups of four. We cut the string into chunks and join the chunks with a space.

chunks.py
from itertools import batched

card = '4111111111111111'
iban = 'SK3112000000198742637541'

groups = [card[i:i + 4] for i in range(0, len(card), 4)]
print(' '.join(groups))

print(' '.join(''.join(group) for group in batched(iban, 4)))

The first version slices the string in steps of four. The second uses itertools.batched, added in Python 3.12, which yields tuples of characters; each tuple is joined into a string first and the strings are then joined with a space.

$ python chunks.py
4111 1111 1111 1111
SK31 1200 0000 1987 4263 7541

Weaving strings

Joining a generator built with zip merges two strings character by character.

weave.py
first = 'ACEGI'
second = 'BDFHJ'

print(''.join(a + b for a, b in zip(first, second)))
print('/'.join(f'{a}{b}' for a, b in zip(first, second)))

word = 'falcon'
print('.'.join(word))
print(''.join(reversed(word)))

Each pair from zip becomes a two-character string. The reversed function returns an iterator, not a string; join turns it back into one.

$ python weave.py
ABCDEFGHIJ
AB/CD/EF/GH/IJ
f.a.l.c.o.n
noclaf

SQL placeholders

SQL statements with a variable number of columns need the same number of placeholders. We build both lists with join.

placeholders.py
import sqlite3

columns = ['name', 'country', 'population']
rows = [
    ('Bratislava', 'Slovakia', 475_000),
    ('Budapest', 'Hungary', 1_686_000),
]

marks = ', '.join('?' * len(columns))
sql = f'INSERT INTO cities ({", ".join(columns)}) VALUES ({marks})'
print(sql)

con = sqlite3.connect(':memory:')
con.execute('CREATE TABLE cities (name TEXT, country TEXT, population INT)')
con.executemany(sql, rows)

for row in con.execute('SELECT * FROM cities'):
    print(row)

con.close()

The expression '?' * len(columns) creates the string ???, and joining it puts a comma between the question marks. We join only column names that we control; the values are passed separately to executemany and never become part of the SQL text.

$ python placeholders.py
INSERT INTO cities (name, country, population) VALUES (?, ?, ?)
('Bratislava', 'Slovakia', 475000)
('Budapest', 'Hungary', 1686000)

Joining bytes

The bytes type has a join method too. The separator and all items must be bytes.

join_bytes.py
headers = [
    b'GET / HTTP/1.1',
    b'Host: example.com',
    b'Connection: close',
]

request = b'\r\n'.join(headers) + b'\r\n\r\n'
print(request)

chunks = [b'\x89PNG', b'\r\n', b'\x1a\n']
print(b''.join(chunks))

We build an HTTP request from header lines joined with \r\n. The empty bytes separator concatenates chunks of binary data, here the signature of a PNG file. This is the usual way to assemble data received in pieces from a socket.

$ python join_bytes.py
b'GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n'
b'\x89PNG\r\n\x1a\n'

Joining paths

Paths look like strings joined with a slash, but '/'.join knows nothing about path rules.

paths.py
import posixpath
from pathlib import PurePosixPath

parts = ['/var/www/', 'site', '/static/', 'app.css']

print('/'.join(parts))
print(posixpath.join(*parts))
print(PurePosixPath('/var/www', 'site', 'static', 'app.css'))

Joining with '/' doubles the slashes. The posixpath.join function avoids that, but it starts again at every absolute component, so '/static/' discards everything before it. With pathlib we pass clean components and let the library insert the separators. For URLs, urllib.parse.urljoin follows the URL resolution rules.

$ python paths.py
/var/www//site//static//app.css
/static/app.css
/var/www/site/static/app.css

A text table

In the last example we use join on three levels to print a table in Markdown syntax.

report.py
cities = [
    ('Bratislava', 'Slovakia', 475_503),
    ('Budapest', 'Hungary', 1_686_222),
    ('Prague', 'Czechia', 1_384_732),
    ('Vienna', 'Austria', 2_005_760),
]

header = ('City', 'Country', 'Population')
table = [header] + [(c, n, f'{p:,}') for c, n, p in cities]
widths = [max(len(row[i]) for row in table) for i in range(len(header))]


def format_row(row):
    cells = (cell.ljust(w) for cell, w in zip(row, widths))
    return '| ' + ' | '.join(cells) + ' |'


rule = '|' + '|'.join('-' * (w + 2) for w in widths) + '|'
lines = [format_row(header), rule]
lines.extend(format_row(row) for row in table[1:])

print('\n'.join(lines))

The widths list holds the width of the widest cell in each column. The format_row function pads each cell and joins the cells with ' | '. The rule line joins dashes with '|', and the final '\n'.join puts the rows on separate lines.

$ python report.py
| City       | Country  | Population |
|------------|----------|------------|
| Bratislava | Slovakia | 475,503    |
| Budapest   | Hungary  | 1,686,222  |
| Prague     | Czechia  | 1,384,732  |
| Vienna     | Austria  | 2,005,760  |

Source

str.join – Python documentation

bytes.join – Python documentation

In this article we have joined strings in Python with the join method. See also Python split string, Python list to string, Python add string, and Python strip string.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.