Converting a list into a string using the join method

by Alex
Converting a list into a string using the join method

The join method in Python is responsible for joining a list of strings using a specific pointer. This is often used when converting a list to a string. For example, this is how you can convert a list of letters of the alphabet into a comma-separated string for saving. The method takes an iterated object as an argument, and since the list meets these conditions, it is fine to use it. Also, the list must consist of strings. If you try to use the function for a list with different contents, the result will be the following message: TypeError: sequence item 0: expected str instance, int found. Let’s look at a short example of combining a list to create a string.

vowels = ["a", "e", "i", "o", "u"]
vowels_str = ",".join(vowels)
print("Vowel string:", vowels_str)

This script will give this result:

Vowel string: a,e,i,o,u

Why is join() a string method and not a list method?

Many people often ask why join() refers to a string and not a list. Wouldn’t that syntax be easier to remember?

vowels_str = vowels.join(",")

This is a popular question on StackOverflow, and here is a simple answer: The join() function can be used with any iterated object, but the result will always be a string, which is why it makes sense to have it as a string API.

Combining a list with multiple data types

Let’s look at a program where an attempt is made to join list items of different types:

names = ['Java', 'Python', 1]
delimiter = ','
single_str = delimiter.join(names)


Traceback (most recent call last):
File "", line 3, in
single_str = delimiter.join(names)
TypeError: sequence item 2: expected str instance, int found

This is just a demonstration that join cannot be used to combine elements of different types. String values only. To avoid this error, turn all list items into strings:

names = ['Java', 'Python', 1]
names = [str(i) for i in names]

Splitting a string with join

You can also use the join() function to split a string by a specific delimiter.

>>> print(",".join("Python"))

If you pass a string as an argument to the function, it will be split into characters at the specified delimiter.

The inverse conversion of a string to a list

In addition to join() there is a function called split() which is used to split a string. It works in a similar way. Let’s take a look at the code:

names = ['Java', 'Python', 'Go']
delimiter = ','
single_str = delimiter.join(names)
print('String: {0}'.format(single_str))
split = single_str.split(delimiter)
print('list: {0}'.format(split))


String: Java,Python,Go
List: ['Java', 'Python', 'Go']

That’s all you need to know about merging and splitting lines.

Related Posts