Python String join() Method
The Python join() method is used to join elements in a sequence with specified characters to produce a new string.
Python String join() Syntax
Join () method syntax:
str.join(sequence)
Python String join() Parameters
- Sequence – The sequence of elements to be concatenated.
Python String join() Return Value
Returns a new string generated by concatenating elements in the specified character sequence.
Python String join() Example#1
Concatenate with an empty string. In this case, we concatenate a list of elements by concatenating.
#!/usr/bin/python3
list1 = ['a', 'p', 'i', 'd', 'e', 'm', 'o', 's']
print("".join(list1))
list1 = " .com "
print("$".join(list1))
Output:
Python String join() Example#2
Join strings and lists using join().
Here, we join the elements of a tuple using the join() method, where we can put any character to join the string.
#!/usr/bin/python3
list1 = ('5', '6', '7', '8')
s = "-"
# joins elements of list1 by '-' and stores in string s
s = s.join(list1)
print(s)
Output:
Python String join() Example#3
Join the string to the collection using join().
In this example, we use a Python collection to concatenate strings.
The collection contains only a unique value, so out of the two sixes, a 6 is printed.
#!/usr/bin/python3
list1 = {'1', '2', '3', '6', '6'}
s = "-#-"
# joins elements of list1 by '-#-' and stores in string s
s = s.join(list1)
print(s)
Output:
Python String join() Example#4
Join strings and a dictionary using join().
When a string is concatenated with a dictionary, it is concatenated with the key of the Python dictionary, not with the value.
#!/usr/bin/python3
dic = {'Api': 1, 'Demos': 2, 'Com': 3}
string = '_'.join(dic)
print(string)
Output: