Tuesday, February 18, 2020

Python String join() Method

If you want to join a sequence of Strings in Python that can be done using join() method. Python join() method returns a string which is created by concatenating all the elements in an iterable.

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

  1. Python String split() Method
  2. Check if String Present in Another String in Python
  3. pass Statement in Python
  4. Namespace And Variable Scope in Python
  5. Interface in Python

You may also like-

  1. Python Installation on Windows
  2. Class And Object in Python
  3. Keyword Arguments in Python
  4. Bubble Sort Program in Python
  5. JVM Run-Time Data Areas - Java Memory Allocation
  6. final Keyword in Java With Examples
  7. BeanPostProcessor in Spring Framework
  8. How to Write a Map Only Job in Hadoop MapReduce