English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Advanced Python knowledge

Python reference manual

Python string join() usage and examples

Python string methods

join() is a string method that returns a string connected with the iterable elements.

The join() method provides a flexible way to concatenate strings. It concatenates each element of the iterable (such as a list, string, and tuple) to the string and returns the concatenated string.

The syntax of join() is:

string.join(iterable)

The join() parameter

The join() method takes an iterable object-Objects that can return their members at once

Some examples of iterable are:

The join() return value

The join() method returns a string concatenated with the elements of the iterable.

If Iterable contains any non-string values, it will triggerTypeErrorException.

Example1:How does the join() method work?

numList = ['1', ''2', ''3', ''4]
seperator = ', ''
print(seperator.join(numList))
numTuple = ('1', ''2', ''3', ''4)
print(seperator.join(numTuple))
s1 = 'abc'
s2 = '123'
""" s2each character is connected to s1in front """ 
print('s1.join(s2): ', s1.join(s2))
""" s1each character is connected to s2in front """ 
print('s2.join(s1): ', s2.join(s1))

When running the program, the output is:

1, 2, 3, 4
1, 2, 3, 4
s1.join(s2): 1abc2abc3
s2.join(s1): a123b123c

Example2:How does the join() method work in sets?

test =  {2', ''1', ''3}
s = ', ''
print(s.join(test))
test = {'Python', 'Java', 'Ruby'}
s = '->-'
print(s.join(test))

When running the program, the output is:

2, 3, 1
Python->->Ruby->->Java

Note:  Sets are an unordered collection of items, and you may get different outputs.

Example3:How does the join() method work in dictionaries?

test =  {'mat': 1, 'that': 2}
s = '-'
print(s.join(test))
test =  {1: 'mat', 2: 'that'}
s = ', ''
# This throws an error
print(s.join(test))

When running the program, the output is:

mat->that
Traceback (most recent call last):
  File "...", line 9, in <module>
TypeError: sequence item 0: expected str instance, int found

The join() method attempts to concatenate the keys of the dictionary (not the values) to the string. If the string key is not a string, it will triggerTypeErrorException. 

Python string methods