Python 3 reference · String Methods
Python String join() Method
Join the strings of an iterable into one string, with this string as the separator between them.
Python 3 Since 3.0
Syntax
str.join(iterable)
Parameters
| Parameter | Description |
|---|---|
iterable |
Strings to join; any non-string item raises TypeError. |
Return value
A new string.
Examples
print(", ".join(["red", "green", "blue"]))
print("".join(["a", "b", "c"]))
print("-".join("abc"))
Output
red, green, blue abc a-b-c
numbers = [1, 2, 3]
print(" + ".join(str(n) for n in numbers), "=", sum(numbers))
Output
1 + 2 + 3 = 6
lines = ["first line", "second line"]
print("\n".join(lines))
Output
first line second line
Common mistakes
- The separator comes first:
", ".join(items), notitems.join(", "). - All items must be strings: convert with
str()ormap(str, items). - Building text with
+=in a loop is slow for long text; collect parts in a list andjoin()once.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
str.split()· Split the string into a list of substrings at a separator. With no separator it splits on any whitespace.str.rsplit()· Split the string into a list from the right. With maxsplit, only the last few splits are made.str.splitlines()· Split the string into a list of lines at line boundaries (\n, \r\n and others), without the line endings.- Python Strings · tutorial