Python str.join() function


In Python, the str.join() method is used to concatenate a sequence of strings (such as a list or tuple) into a single string, with a specified separator placed between each pair of strings. This method is particularly useful for combining elements of an iterable into a formatted string.

Syntax

str.join(iterable)
  • iterable: A sequence (like a list, tuple, or string) containing strings to be joined. Non-string elements will raise a TypeError.

Example Usage

  1. Basic usage with a list:
words = ["Hello", "world"] result = " ".join(words) print(result) # Output: "Hello world"
  1. Using a different separator:
words = ["apple", "banana", "cherry"] result = ", ".join(words) print(result) # Output: "apple, banana, cherry"
  1. Joining with no separator:
words = ["Python", "is", "awesome"] result = "".join(words) print(result) # Output: "Pythonisawesome"
  1. Joining with newline characters:
lines = ["First line", "Second line", "Third line"] result = "\n".join(lines) print(result) # Output: # First line # Second line # Third line
  1. Joining strings from a tuple:
tuple_of_strings = ("Join", "these", "words") result = " - ".join(tuple_of_strings) print(result) # Output: "Join - these - words"

Important Notes

  • TypeError: If any element in the iterable is not a string, a TypeError will be raised. You can convert non-string types to strings before joining them, e.g., using map().
numbers = [1, 2, 3] result = ", ".join(map(str, numbers)) print(result) # Output: "1, 2, 3"

Summary

  • Use str.join() to concatenate a sequence of strings with a specified separator.
  • It's a clean and efficient way to create a single string from multiple string elements.
  • Remember that str.join() only works with iterables of strings; any non-string types need to be converted to strings first.