Given a list, write a Python program to convert the given list to string. There are various situations we might encounter when a list is given and we convert it to string. For example, conversion to string from the list of string or the list of integer.
Example:
Input: ['Geeks', 'for', 'Geeks'] Output: Geeks for Geeks Input: ['I', 'want', 4, 'apples', 'and', 18, 'bananas'] Output: I want 4 apples and 18 bananasLet’s see various ways we can convert the list to string.
Method #1: Iterate through the list and keep adding the element for every index in some empty string.
Python3
def listToString(s):
str1 = ""
for ele in s:
str1 += ele
return str1
s = ['Geeks', 'for', 'Geeks']
print(listToString(s))
Method #2: Using .join() method
Python3
def listToString(s):
str1 = " "
return (str1.join(s))
s = ['Geeks', 'for', 'Geeks']
print(listToString(s))
But what if the list contains both string and integer as its element. In those cases, above code won’t work. We need to convert it to string while adding to string.
Method #3: Using list comprehension
Python3
s = ['I', 'want', 4, 'apples', 'and', 18, 'bananas']
listToStr = ' '.join([str(elem) for elem in s])
print(listToStr)
Output:
I want 4 apples and 18 bananasMethod #4: Using map() Use map() method for mapping str (for converting elements in list to string) with given iterator, the list.
Python3
s = ['I', 'want', 4, 'apples', 'and', 18, 'bananas']
listToStr = ' '.join(map(str, s))
print(listToStr)
Output:
I want 4 apples and 18 bananasMethod #5: Using enumerate function
Python3
s = ['I', 'want', 4, 'apples', 'and', 18, 'bananas']
listToStr = ' '.join([str(elem) for i,elem in enumerate(s)])
print(listToStr)
Output
I want 4 apples and 18 bananasMethod #6: Using in operator
Python3
s = ['Geeks', 'for', 'Geeks']
for i in s:
print(i,end=" ")
How can I convert a list to a string using Python?
Aran-Fey
36.4k10 gold badges96 silver badges141 bronze badges
asked Apr 11, 2011 at 8:51
3
Use ''.join:
xs = ['1', '2', '3'] s = ''.join(xs)If the list contains integers, convert the elements to string before joining them:
xs = [1, 2, 3] s = ''.join(str(x) for x in xs)
Mateen Ulhaq
22.2k16 gold badges86 silver badges127 bronze badges
answered Apr 11, 2011 at 8:52
Senthil KumaranSenthil Kumaran
52.3k14 gold badges90 silver badges127 bronze badges
7
>>> xs = [1, 2, 3] >>> " ".join(str(x) for x in xs) '1 2 3'
Mateen Ulhaq
22.2k16 gold badges86 silver badges127 bronze badges
answered Apr 11, 2011 at 8:53
Andrey SboevAndrey Sboev
7,3241 gold badge19 silver badges35 bronze badges
2
xs = ['L', 'O', 'L'] lol_string = ''.join(map(str, xs))
Mateen Ulhaq
22.2k16 gold badges86 silver badges127 bronze badges
answered Apr 11, 2011 at 8:56
NathanNathan
5,98510 gold badges44 silver badges54 bronze badges
4