When working with text in Python, you’ll often need to combine multiple strings into one. The Python String join() method is the most efficient way to achieve this. It takes an iterable (like a list, tuple, set, dictionary, or even another string) and concatenates all its elements into a single string, inserting a specified separator between them
join() method syntax
str.join(iterable)
Here iterable is an object which can return its element one at a time like list, tuple, set, dictionary, string.
str represents a separator that is used between the elements of iterable while joining them.
All the values in iterable should be String, a TypeError will be raised if there are any non-string values in iterable.
Python join() method examples
1. join method with a tuple.
cities = ('Chicago','Los Angeles','Seattle','Austin')
separator = ':'
city_str = separator.join(cities)
print(city_str)
Output
Chicago:Los Angeles:Seattle:Austin
2. Python join() method with a list of strings.
cities = ['Chicago','Los Angeles','Seattle','Austin'] separator = '|' city_str = separator.join(cities) print(city_str)
Output
Chicago|Los Angeles|Seattle|Austin
3. TypeError if non-string instance is found.
cities = ['Chicago','Los Angeles','Seattle','Austin', 3] separator = '|' city_str = separator.join(cities) print(city_str)
Output
city_str = separator.join(cities)
TypeError: sequence item 4: expected str instance, int found
In the list there is an int value too apart from strings therefore TypeError is raised while attempting to join the elements of the list.
4. Python join() method with a Set. Since set is an unordered collection so sequence of elements may differ.
cities = {'Chicago','Los Angeles','Seattle','Austin'}
separator = '-'
city_str = separator.join(cities)
print(city_str)
Output
Austin-Los Angeles-Chicago-Seattle
5. join() method with a Dictionary. In case of dictionary keys are joined not the values.
cities = {'1':'Chicago','2':'Los Angeles','3':'Seattle','4':'Austin'}
separator = '-'
city_str = separator.join(cities)
print(city_str)
Output
1-2-3-4
That's all for this topic Python String join() Method. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-