Python Tutorial Python Advanced Python References Python Libraries

Python String - join() Method



The Python join() method returns a string which contains all elements of an iterable separated by the specified character(s). For this method, all elements of the iterable must be string.

Syntax

string.join(iterable)


Parameters

iterable Required. iterable object like list, tuple, set, string , dictionary etc with all string elements.

Return Value

Returns a string which contains all elements of an iterable separated by the specified character(s).

Example:Joining all elements of a list

In the example below, join() method is used to join all elements of the given list, each separated by a single whitespace.

MySeparator = " "
MyList = ["John", "25", "London"]
print(MySeparator.join(MyList))

The output of the above code will be:

John 25 London

Example: Joining all keys of a dictionary

In the example below, join() method is used to join all keys of the dictionary, each separated by @.

MyDict = {
   "name": "John",
   "age": 25,
   "city": "London"
}
MySeparator = "@"
print(MySeparator.join(MyDict))

The output of the above code will be:

name@age@city

❮ Python String Methods