Python String join()

Created with Sketch.

Python String join()

Summary: in this tutorial, you’ll learn how to use the Python String join() method to concatenate strings in an iterable into one string.

Introduction to the Python String join() method

The string join() method returns a string which is the concatenation of strings in an iterable such as a tuple, a list, a dictionary, and a set.

The following shows the syntax of the join() method:

str.join(iterable)

 

The str will be the separator between elements in the result string.

If the iterable contains any non-string value, the join() method will raise a TypeError. To fix it, you need to convert non-string values to strings before calling the join() method.

The join() method has many practical applications. For example, you can use the join() method to compose a row for a CSV file.

Python string join examples

Let’s take some examples of using the string join() method.

1) Using string join() method to concatenate multiple strings into a string

The following example uses the string join() method to concatenate a tuple of strings without a separator:

colors = ('red', 'green', 'blue')
rgb = ''.join(colors)
print(rgb)

 

Output:

redgreenblue

 

The following example uses the string join() method with the comma separator (,):

colors = ('red', 'green', 'blue')
rgb = ','.join(colors)
print(rgb)

 

Output:

red,green,blue

 

2) Using string join() method to concatenate non-string data into a string

The following example uses the join() method to concatenate strings and numbers in a tuple to a single string:

product = ('Laptop', 10, 699)
result = ','.join(product)
print(result)

 

Output:

TypeError: sequence item 1: expected str instance, int found

Code language: JavaScript (javascript)

It issued a TypeError because the tuple product has two integers.

To concatenate elements in the tuple, you’ll need to convert them into strings before concatenating. For example:

product = ('Laptop', 10, 699)
result = ','.join(str(d) for d in product)
print(result)

 

Output:

Laptop,10,699

 

How it works.

  • First, use a generator expression to convert each element of the product tuple to a string.
  • Second, use the join() method to concatenate the string elements

Summary

  • Use the join() method to concatenate multiple strings in an iterable into one string.

Leave a Reply

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