Python String join() Method (original) (raw)
Last Updated : 12 Nov, 2024
The join() method in Python is used to concatenate the elements of an iterable (such as a list, tuple, or set) into a single string with a specified delimiter placed between each element.
Lets take a simple example tojoin list of string using join() method.
Joining a List of Strings
In below example, we use **join() method to combine a **list of strings into a **single string with each string separated by a **space.
Python `
a = ['Hello', 'world', 'from', 'Python'] res = ' '.join(a) print(res)
`
Output
Hello world from Python
Table of Content
- Syntax of join()
- Examples of join() Method on Different Data Types
- Frequently Asked Questions on Python String Join() Method
Syntax of join()
separator.join(iterable)
Parameters:
- **separator: The string placed between elements of the iterable.
- **iterable: A sequence of strings (e.g., list, tuple etc) to join together.
Return Value:
- Returns a single string formed by joining all elements in the iterable, separated by the specified separator
- If the iterable contains any non-string values and it raises a **TypeError exception.
Examples of join() Method on Different Data Types
Below are examples of how join() method works with different data types.
Using join() with Tuples
The **join() method works with any iterable containing strings, including **tuples.
Python `
s = ("Learn", "to", "code")
Separator "-" is used to join strings
res = "-".join(s) print(res)
`
Using join() with set
In this example, we are joining set of String.
Python `
s = {'Python', 'is', 'fun'}
Separator "-" is used to join strings
res = '-'.join(s) print(res)
`
**Note: Since **sets are unordered, the resulting string may appear in any order, such as “fun is Python” or “Python is fun”.
Using join() with Dictionary
When using the **join() method with a dictionary, it will only join the **keys, not the values. This is because **join() operates on iterables of strings and the default iteration over a dictionary returns its **keys.
Python `
d = {'Geek': 1, 'for': 2, 'Geeks': 3}
Separator "_" is used to join keys into a single string
res = '_'.join(d)
print(res)
`