Convert List [Array] to String

The fastest way to convert a list (array) to a string is to use the join function.

The join function concatenates all elements inside the list and uses spaces as separators.

The result of this code is this string.

This is a string

This code is easily modifiable when you want to change a separator to a different one. Let’s try a comma.

By changing one character, you are getting this result.

This,is,a,string

Int List to String

If you try to convert a list that contains integer values instead of strings, Python is going to return an error.

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

We have to convert integer values to strings before we can join them. For this task, we are going to use the for loop.

The problem with this approach is that it adds a comma at the beginning of the string which we want to avoid. That’s why we add a line my_string = my_string[1:] that removes the first character and assigns this value to my_string.

1,22,13,214

This result can be also achieved by using a range inside the loop and then adding a separator after the first iteration (which starts from 0).

The result is the same.

1,22,13,214

The quickest and most Pythonic way to do it is to convert integers to string in one line. Here’s the code.

The result is the same as before but the code uses only two lines.

Map List

Another simple way to convert a list of ints to a string is to use the map function. There is no need to use loops in this case.

In our case, the map function takes a list as a second parameter and applies the str function. In other words, it converts integers inside the list to strings. The join function concatenates these elements, using a comma as a separator. The result is the same as in previous examples.

1,22,13,214

Nested List

We can also convert a list of lists to a string. The elements in our list consist of multiple smaller lists. In these lists are both strings and integer values. We have to convert these values to strings and then join them to create a one-dimensional list.

This is what the code looks like:

This is what the result looks like:

['1 1', '2', 'This is 3']

This list has to be joined to create a single string. We can use the method from the first example. The full code looks like this:

As expected, the result is a string.

1 1 2 This is 3

Convert List to String With Quotes

String values are written inside quotes. If you want to add quotes to a string you can’t just add another quote between quotes, because Python will return the syntax error. If you use three quotes “””text”””, the result will be the same as with single quotes.

SyntaxError: invalid syntax

What you have to do is to use different quotes. You can do it for single quotes.

Result:

This is 'text' string

You can also do it for double quotes.

Result:

This is "text" string

You can also combine both quotes.

Result:

This is "text" 'string'