Python’s str.join() method combines strings from an iterable into one string, placing the string before the dot between each item. For example, ', '.join(['red', 'green', 'blue']) returns 'red, green, blue'; every item in the iterable must already be a string.
What Python’s join() method does
join() is a method on string objects, not a standalone function. The string that calls it is called the separator or delimiter: it is inserted between neighboring items, but not before the first item or after the last. This makes it useful for turning a sequence of text values into a sentence, a comma-separated list, a file path, or another formatted string.
The method returns a new string and does not change the original iterable or its elements. For instance, joining the list ['north', 'south'] with ' / ' produces 'north / south', while the original list remains as it was. The separator can be any string, including an empty string.
', '.join(items)places a comma and a space between items.'-'.join(items)places a hyphen between items.''.join(items)places nothing between items.
Syntax and the separator
The general syntax is separator.join(iterable). The iterable can be a list, tuple, generator, or another object that yields strings. The separator must itself be a string. Because the separator is the object before .join(), the direction can feel backward at first: write the delimiter first, then call join() with the items to combine.
For example, the following expressions use different separators but the same values:
' '.join(['Ada', 'Lovelace'])returns'Ada Lovelace'.'::'.join(['host', 'port'])returns'host::port'.''.join(['Py', 'thon'])returns'Python'.
A separator is inserted only between items. Thus, '--'.join(['a', 'b', 'c']) returns 'a--b--c', not '--a--b--c--'. If a leading or trailing delimiter is required for a particular format, add it explicitly or build it as part of the desired output.
Joining lists, tuples, and other iterables
A list is a common input, but join() accepts an iterable rather than requiring a list specifically. A tuple works in the same way, and a generator expression can produce values as needed:
' | '.join(('one', 'two', 'three'))returns'one | two | three'.', '.join(str(number) for number in range(1, 4))returns'1, 2, 3'.
The generator example converts each integer to text before joining it. A dictionary is iterable too, but iterating over a dictionary yields its keys. Therefore, ', '.join({'a': 1, 'b': 2}) joins the keys, resulting in 'a, b' (the insertion order of the keys is preserved in modern Python). To join values, pass dictionary.values(); to join key-value pairs, format each pair first.
For example, with prices = {'tea': 3, 'coffee': 4}, an expression such as ', '.join(f'{name}: {price}' for name, price in prices.items()) creates 'tea: 3, coffee: 4'. This works because each f-string expression produces a string for the join operation.
Joining values that are not strings
One of the most common surprises is that join() does not automatically convert numbers, None, or other objects to text. If any yielded item is not a string, Python raises a TypeError. For example, ', '.join([1, 2, 3]) fails even though each number can be displayed as text.
Convert the values deliberately before joining. For a list of integers, use ', '.join(map(str, numbers)) or a generator expression such as ', '.join(str(number) for number in numbers). Both produce a string like '1, 2, 3' when numbers is [1, 2, 3].
Choose the conversion with the output in mind. str() produces human-readable text, while repr() is intended to provide a representation useful for debugging and may include quotes around strings. If a value could be None, decide whether the output should say 'None', use an empty field, or omit that value entirely. For example, filtering first with if item is not None omits missing values; converting every item with str(item) renders a missing value as the literal text 'None'.
Strings are iterable too
A string is itself an iterable of one-character strings. Consequently, passing a single string to join() works, but it joins its characters rather than treating the whole string as one item. For example, '-'.join('cat') returns 'c-a-t'. This behavior can cause accidental character-by-character separators if a function expected a list of words but receives one string instead.
If a string should be treated as one item, wrap it in a one-element list or tuple: '-'.join(['cat']) returns 'cat'. This does not add a separator, because there is no pair of neighboring elements. Likewise, joining an empty string yields an empty string because the input has no characters.
Empty and single-item inputs
Knowing the boundary cases helps when building output dynamically. Joining an empty iterable returns an empty string, regardless of the separator: ', '.join([]) returns ''. Joining one string returns that string unchanged: ', '.join(['only']) returns 'only'. No separator is needed when there is only one item.
These results are often convenient for optional lists. Rather than adding special code for zero or one values, a program can join the list directly. However, if an empty result has a special meaning in an application, such as “no selection,” handle that meaning separately instead of assuming the method will supply a placeholder.
Common errors and how to fix them
Most join() mistakes come from the input type or from placing the method call in the wrong direction. Check the value being passed to join(), including values produced by a generator or fetched from a dictionary.
- TypeError: sequence item … expected str instance. At least one item is not a string. Convert values intentionally with
str(), or format them while generating the items. - Trying to call join on a list.
items.join(', ')is backwards. Use', '.join(items); the separator is the string that owns the method. - Unexpected separators between letters. The input may be a string rather than a list of strings. Inspect its type or wrap the whole string in a one-item list when appropriate.
- Unexpected dictionary output. Iterating over a dictionary produces keys. Use
values()oritems()if that is what the output requires.
When a type error is confusing, inspect the iterable’s contents and types. A list annotation or a variable name such as words does not guarantee its elements are strings; data read from a file, API, or user input may have a different type than expected.
Choosing a separator and handling text
The separator should match the format you are producing. Use a comma and space for readable lists, a newline ('\n') to put each item on its own line, or a path-handling library rather than string joining when constructing filesystem paths. Path separators and path rules vary by operating system, so os.path.join() or pathlib.Path is generally more appropriate for paths than plain str.join().
Unicode text works with ordinary string joining. A separator may contain non-ASCII characters, such as ' → ' or ' • ', and strings can contain accented letters or characters from other writing systems. Joining does not normalize Unicode or translate text; it simply places the separator between the given strings. If text comparison or normalization matters, use the appropriate Unicode handling separately.
join() compared with concatenation and alternatives
For a small, fixed number of values, the plus operator is often clear: first + ' ' + last. For a collection of an arbitrary number of strings, join() expresses the operation directly and is a standard choice. Repeatedly adding strings inside a loop can create unnecessary intermediate results in some situations, so collecting pieces and joining them at the end is a useful general pattern.
Other tools suit different jobs:
- F-strings are convenient when combining a few named values with labels or formatting, as in
f'{name}: {score}'. To combine many already prepared values with a delimiter,join()is usually more direct. str.format()and the percent operator provide other ways to format individual values, but they do not replace the basic task of inserting one separator between an iterable’s items.print()accepts multiple arguments and has asepoption, but it writes output to a stream and returnsNone; it does not return the combined string. Usejoin()when the result needs to be stored, passed to another function, or returned.split()is related but does the opposite kind of work: it breaks a string into a list around a chosen delimiter. Joining the resulting pieces with the same delimiter can reconstruct the text when the split operation has not discarded information.
Frequently Asked Questions
Is join() a Python function or a string method?join() is a method of the str type. Call it on the separator string, as in '/'.join(parts), rather than calling a standalone join(parts) function.
Does join() add a separator at the beginning or end?
No. It inserts the separator only between adjacent items. If you need a leading or trailing delimiter, add it explicitly to the result or include the relevant text in your formatting.
Can join() combine integers?
Not directly. Convert each integer to a string first, for example with ', '.join(map(str, numbers)). If values have special formatting requirements, format them before joining.
What does an empty separator do?
An empty separator inserts no characters between items. For example, ''.join(['data', 'base']) returns 'database'.
Can I use join() with a generator?
Yes. A generator that yields strings can be passed directly, such as ', '.join(str(n) for n in range(3)), which returns '0, 1, 2'. The generated values still must be strings by the time they reach join().
Is bytes.join() the same as str.join()?
They serve a similar purpose but operate on different types. A bytes separator joins bytes-like values and returns bytes; a string separator joins strings and returns str. Convert or decode data deliberately rather than mixing text and binary values.
Related
- SQL Split Syntax: Split Strings by Delimiter
- Split in SQL: Practical Methods for Common Databases
- T-SQL STRING_SPLIT: Syntax, Order, and Examples
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel: Highlight the Bottom 10 Values in RedTo highlight the 10 lowest values in red in Excel, select the cells containing your numbers, then choose…
- Conditional Formatting for Overdue Dates in Excel: GuideIn Excel for Microsoft 365 on Windows, select the date cells, choose Home > Conditional Formatting > New…
- How to Delete Highlighted Cells in ExcelTo delete cells highlighted with a particular fill color in Excel for Microsoft 365 on Windows, use Home…
- Excel Data Validation Button: Where to Find and Use ItIn Excel for Microsoft 365 on Windows, find the Data Validation button on the Data tab, in the…
- Text Split in Excel: How to Separate Data into ColumnsYes. In Excel for Microsoft 365 on Windows, select the cells and choose Data > Text to Columns…
- How to Add the Same Header in Excel on Every SheetTo add the same print header to every worksheet in an Excel workbook, select and group the sheets,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.