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
- iterable: A sequence (like a list, tuple, or string) containing strings to be joined. Non-string elements will raise a
TypeError
.
Example Usage
- Basic usage with a list:
- Using a different separator:
- Joining with no separator:
- Joining with newline characters:
- Joining strings from a tuple:
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., usingmap()
.
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.