Python join() is an inbuilt string function in Python used to join elements of the sequence separated by a string separator. This function joins elements of a sequence and makes it a string.
Example:
Python3
str = '-'.join('hello')
print(str)
|
Output:
h-e-l-l-o
Python String join() Syntax
Syntax: string_name.join(iterable)
Parameters:
- Iterable – objects capable of returning their members one at a time. Some examples are List, Tuple, String, Dictionary, and Set
Return Value: The join() method returns a string concatenated with the elements of iterable.
Type Error: If the iterable contains any non-string values, it raises a TypeError exception.
String join() in Python Examples
Joining with an Empty String
Here, we join the list of elements using the join method.
Python3
list1 = ['g', 'e', 'e', 'k', 's']
print("".join(list1))
list1 = " geeks "
print("$".join(list1))
|
Output:
geeks
$g$e$e$k$s$
Joining String with Lists using Python join()
Here, we join the tuples of elements using the join() method in which we can put any character to join with a string.
Python3
list1 = ('1', '2', '3', '4')
s = "-"
s = s.join(list1)
print(s)
|
Output:
1-2-3-4
Joining String with Sets using join()
In this example, we are using a Python set to join the string.
Note: Set contains only unique value therefore out of two 4 one 4 is printed.
Python3
list1 = {'1', '2', '3', '4', '4'}
s = "-#-"
s = s.join(list1)
print(s)
|
Output:
1-#-3-#-2-#-4
Joining String with a Dictionary using join()
When joining a string with a dictionary, it will join with the keys of a Python dictionary, not with values.
Python3
dic = {'Geek': 1, 'For': 2, 'Geeks': 3}
string = '_'.join(dic)
print(string)
|
Output:
'Geek_For_Geeks'
Joining a list of Strings with a Custom Separator using Join()
In this example, we have given a separator which is separating the words in the list and we are printing the final result.
Python3
words = ["apple", "", "banana", "cherry", ""]
separator = "@ "
result = separator.join(word for word in words if word)
print(result)
|
Output :
apple@ banana@ cherry
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
16 May, 2023
Like Article
Save Article