Skip to main content
Python String join Example

Python String join Example

This Python tutorial will show you how to join strings arrays. The string method join() returns a string concatenated with the elements of an iterable.

It concatenates each element of an iterable (such as a list, string, or tuple) to the string and returns the result.

The syntax of join() is:

string.join(iterable)

If the iterable contains any non-string values, a TypeError exception is thrown..

Whereas join() Parameters is:

  • iterable – Objects that can return its members one at a time. Iterables include List, Tuple, String, Dictionary, and Set..

Checkout other python tutorials:

Join Array String

Let’s create a string array and join with separator.

numList = ['5', '7', '8', '10']
seperator = ', '
print(seperator.join(numList))

Output:

5, 7, 8, 10

Join Array Tuple

We’ll create a string array and join with separator.

numTuple = ('5', '7', '9', '13')
seperator = ', '
print(seperator.join(numTuple))

Output:

5, 7, 9, 13

Join with String Seperater

We can also use more than one character string as a separator.

s1 = 'adam' 
s2 = '345'
""" Each character of s2 is concatenated to the front of s1"""
print('s1.join(s2):', s1.join(s2))

Output:

s1.join(s2): 3adam4adam5

String Joins on Object Array

The built-in string constructor will automatically call obj.str:

''.join(map(str,list))

String Join With Sets

We can also apply join method on sets. Let’s take a look simple example –

seta =  {'7', '5', '3'}<br>
s = ', '<br>
print(s.join(seta))

Output:

 5, 7, 3

join() method with dictionaries?

The join() method also work with dictionaries. Let’s create dictionaries and apply join –

dic =  {'fname': 'adam', 'lname': 'joe'}
s = ', '
print(s.join(dic))
<strong>Output:</strong> 
fname, lname

The join() method tries to concatenate the key (not value) of the dictionary to the string. If the key of the string is not a string, it raises TypeError exception.

Leave a Reply

Your email address will not be published. Required fields are marked *