
Problem –
You want to convert a list to string in Python.
Solution –
To convert a list to a string in python, we can use the str.join() method. The str.join() method returns a string by joining all the elements of a iterable separated by a string separator.
syntax –
string.join(iterable)
Examples –
In [1]: lst = ['Python', 'is', 'awesome']
In [2]: ''.join(lst)
Out[2]: 'Pythonisawesome'
In [3]: ' '.join(lst)
Out[3]: 'Python is awesome'
To convert the elements of the lists that are not string, we need to first convert them to a string before joining them.
In [4]: # using list comprehension
In [5]: lst2 = [1, 2, 3]
In [6]: ''.join([str(element) for element in lst2])
Out[6]: '123'
In [7]: # using map function
In [8]: ''.join(map(str, lst2))
Out[8]: '123'