Python String join() Method



The Python String join() method takes all the elements in an iterable (such as list, string, tuple) separated by the given separator and joins them into one string.

A separator represents the delimiter which is used to separate the given string. These delimiters can be (), [], {}, ; etc.

For instance, in the iterable “[‘6’, ‘8’, ‘9’]”, if we provide a separator “-”, then the string after joining becomes “6-8-9”.

Syntax

Following is the syntax of Python String join() method:

str.join(sequence)

Parameters

  • sequence − This is a sequence of the elements that needs to be joined.

Return Value

This method returns a string, which is the concatenation of the strings in the iterable. The separator between elements is the string providing this method.

Special Case: If the iterable consists of any non-string values including byte objects, a TypeError Exception is raised.

Example

Following is an example where a sequence of string is joined using Python String join() method with the delimiter “-”. The result is then returned:

s = "-";
seq = ("a", "b", "c"); # This is sequence of strings.
print s.join( seq )

Following is the output of the above code:

a-b-c

Example

In the following example all the items in the given dictionary is joined into a string using the word “MATCH” as a separator:

Dictionary = {"Player":"Sachin Tendulkar", "Sports":"Cricket"}
# Providing the separator
sep = "MATCH"
# Joining the items in the dictionary with the given string
res = sep.join(Dictionary)
print(res)

Output of the above code is as follows:

PlayerMATCHSports

Note: The join() method will join the keys of the dictionary with the string seperator, not the values.

Example

In the example given below Python string join() method is used to join the set with the character “#”. Since the set allows only unique values, only one value is printed out of the repeated values (in this case '9'):

sets = {'9','7', '2','9','3','9'}
character = "#"
# storing in the string 
res = character.join(sets)
print(res)

While executing the above code we get the following output:

2#3#7#9

Example

In the following example, a TypeError is raised because the elements of the iterable is not in string:

numbers = (3,6,7,4,7,4,5,32,98,35)
char = "*"
print (char.join(numbers))

When we run above program, it produces following error:

Traceback (most recent call last):
   File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in 
      print (char.join(numbers))
TypeError: sequence item 0: expected str instance, int found
python_strings.htm
Advertisements