Python List to String Conversion

Filed Under: Python

Sometimes we want to convert the list to a string so that we can print it or log it for debugging purposes. In this tutorial, we will learn how to convert a list to string in a Python program.

Python List to String Conversion

If the list contains a string, int, floats then its elements values are getting printed when we print the list.


l1 = [1, 2, 3]
print(l1)

l1 = ['A', 'B', 'C']
print(l1)

l1 = ['A', 'B', 'C', 1, 2, 3.5]
print(l1)

Output:


[1, 2, 3]
['A', 'B', 'C']
['A', 'B', 'C', 1, 2, 3.5]

If you don’t want brackets in the output, you can use string strip() function or slicing to remove them.


print(str(l1).strip('[]'))
print(str(l1)[1:-1])

Output:


'A', 'B', 'C', 1, 2, 3.5
'A', 'B', 'C', 1, 2, 3.5

Python List of Objects to String Conversion

Let’s see what happens when our list contains custom objects.


class Data:
    id = 0

    def __init__(self, i):
        id = i

l1 = [Data(10), Data(20)]
print(l1)

Output:


[<__main__.Data object at 0x10f3dd320>, <__main__.Data object at 0x10f3dd2e8>]

The information is not useful because it doesn’t contain any information about Data objects.

When we print a list, it tries to invoke its elements __repr__() function. Since our object doesn’t define its own repr() function, its superclass object repr() is called which prints this information.

Let’s define __repr__() function for Data class as follows:


    def __repr__(self):
        return f'Data[{self.id}]'

Now the output of above print statement will be:


[Data[0], Data[0]]

Sometimes an object defines only __str__() function and doesn’t define __repr__() function. In that case, we can convert the list to string by calling str() function on its elements.

This can be done by using string join() function with an iterator as argument or by using map() function.

Let’s define __str__() function for Data class as:


    def __str__(self):
        return f'D[{self.id}]'

Now we can get string representation of the list elements and print it using following code:


print(', '.join(map(str, l1)))
print(', '.join(str(e) for e in l1))

Output:


D[0], D[0]
D[0], D[0]

Note that if __str__() function is not defined for an object, str() function fallback to calling __repr__() function. In that case __repr__() should return string object.

If we remove __str__() function from Data class, then above join() snippets output will be:


Data[0], Data[0]
Data[0], Data[0]

We can specify our own delimiter when using join() function.


print('|'.join(map(str, l1)))
print('#'.join(str(e) for e in l1))

Output:


D[0]|D[0]
D[0]#D[0]
You can checkout complete python script and more examples from our GitHub Repository.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages