Python program for converting a list to a string



There are various situations that we can run into when given a list and we convert it to a string. For example, converting to a string from a list of strings or a list of integers.

Example :

 Input: [`Geeks`,` for`, `Geeks` ] Output: Geeks for Geeks Input: [`I`,` want`, 4, `apples`,` and`, 18, `bananas`] Output: I want 4 apples and 18 bananas 

Let`s let`s see how we can convert a list to a string.

Method # 1:
Iterate through the list and keep adding an element for each index to some empty string.

Exit :

 Python.Engineering 

Method # 2: Using the .join () method

# Python program to convert list to string

 
# Function to convert

def listToString (s) : 

 

# initialize p empty string

str1 = "" 

 

# line move

  for ele in s: 

str1 + = ele 

 

# returned string

  return str1 

 

  
# Driver code

s = [ `Geeks` , ` for` , `Geeks` ]

print (listToString (s)) 

# Python program to convert the list
# to a string using the join () function

 
# Function to convert

def listToString ( s): 

 

# initialize empty string

str1 = ""  

 

# returned string

return (str1.join (s))

  

 
# Driver code

s = [ `Geeks` , `for` , `Geeks` ]

print (listToString (s)) 

Exit :

 Geeks for Geeks 

But what if the list contains a string and an integer as an element. In these cases, the above code will not work. We need to convert it to a string when added to a string.

Method # 3: Using the comprehension list

# Python program to convert a list
# to a string using a list comprehension

 

s = [ `I` , ` want` , 4 , `apples` , `and` , 18 , `bananas` ]

  
# using comprehension list

listToStr = `` . join ([ str (elem) for elem in s])

 

print (listToStr) 

Output:

 I want 4 apples and 18 bananas 

Method # 4: Using the card ()
Use the method map () to display str (to convert elements in a list to a string) with a given iterator, list.

# Python program for converting cn claim
# to a line using a list comprehension

 

s = [ ` I` , `want` , 4 , `apples` , `and` , 18 , ` bananas` ]

 
# using comprehension list

listToStr = `` . join ( map (  str , s))

 

print (listToStr) 

Exit :

 I want 4 apples and 18 bananas