The join() function in python helps to create a new string by joining all the elements of the given iterable using a string separator.
string.join(iterable) #where iterable may be List, Tuple, String, Dictionary and Set.
The join() function takes a single parameter. The function will raise a TypeError exception if the iterable contains any non-string values,
Parameter | Description | Required / Optional |
---|---|---|
iterable | Any iterable object where all the returned values are strings | Required |
The return value is always a concatenated string. If we are using a dictionary as an iterable, the returned values will be the keys, not the values.
Input | Return Value |
---|---|
Iterable | string |
# .join() with lists
List = ['5', '4', '3', '2']
separator = ', '
print(separator.join(List))
# .join() with tuples
Tuple = ('5', '4', '3', '2')
print(separator.join(Tuple))
string1 = 'xyz'
string2 = '123'
# each element of string2 is separated by string1
# '1'+ 'xyz'+ '2'+ 'xyz'+ '3'
print('string1.join(string2):', string1.join(string2))
# each element of string1 is separated by string2
# 'x'+ '123'+ 'y'+ '123'+ 'z'
print('string2.join(string1):', string2.join(string1))
Output:
5, 4, 3, 2 5, 4, 3, 2 string1.join(string2): 1xyz2xyz3 string2.join(string1): x123y123z
# .join() with sets
num = {'5', '4', '3'}
separator = ', '
print(separator.join(num))
string = {'Apple', 'Orange', 'Grapes'}
separator = '->->'
print(separator.join(string))
Output:
5, 4, 3 Apple->->Orange->->Grapes
print(chr(-1))
print(chr(1114112))
Output:
ValueError: chr() arg not in range(0x110000) ValueError: chr() arg not in range(0x110000)
# .join() with dictionaries
dict = {'test': 1, 'with': 2}
seperator = '->'
# joins the keys only
print(seperator.join(dict))
dict = {1: 'test', 2: 'with'}
seperator = ', '
# this gives error since key isn't string
print(seperator.join(dict))
Output:
test->with Traceback (most recent call last): File "...", line 12, inTypeError: sequence item 0: expected str instance, int found