English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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() method takes an iterable object-Objects that can return their members at once
Some examples of iterable are:
Native data types - List,Tuple,String,DictionaryAndSet
File object and usage__iter__ ()or an object defined by the __getitem()__ method
The join() method returns a string concatenated with the elements of the iterable.
If Iterable contains any non-string values, it will triggerTypeErrorException.
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
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.
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.