splitting
str.join
Returns a string built by concatenating every string in the iterable, separated by the string on which join is called. Every element of the iterable must be a str, or TypeError is raised.
str.join(iterable) Parameters
| Parameter | Purpose |
|---|---|
| iterable | iterable of strings to concatenate |
| self | the separator string placed between elements |
Examples
>>> ', '.join(['a', 'b', 'c'])
'a, b, c' canonical CSV-style join
>>> ''.join(['h', 'i'])
'hi' empty separator concatenates
>>> '-'.join(str(n) for n in range(3))
'0-1-2' generator expression works; note the explicit str() cast
>>> ','.join(['a', 1])
Traceback (most recent call last):
...
TypeError: sequence item 1: expected str instance, int found non-str items raise TypeError
Gotcha
Every element must already be a str — use map(str, ...) or a generator with str() first. join is much faster than repeated += for building large strings.
Related methods
str.split
Returns a list of substrings split at each occurrence of sep. If sep is None (default), runs of any whitespace are the separator and leading/trailing whitespace is discarded; if sep is given, empty fields between adjacent separators are preserved.
str.splitlines
Splits the string at universal line boundaries (\n, \r, \r\n, and other Unicode line terminators). Unlike split('\n'), it does not produce a trailing empty string when the input ends with a newline.
str.partition
Splits the string at the first occurrence of sep and returns a 3-tuple (before, sep, after). If sep is not found, returns (original, '', '') — so unpacking is always safe.