The list is a popular datatype used in Python programming language. The list may contain different types of items like integer, string, list, etc. In some cases, you may need to convert the list or list items into a string.
Covert List To String Using for
The simplest way to convert a list into a string is using the for keyword where every item in the list will be iterated with the for keyword. In every iteration, the current item will be converted into a string and added into the string variable.
mylist = [ 1 , 2 , "poftut" , "ahmet"] mystr="" for x in mylist: mystr += str(x) print(mystr)
Covert List To String Using join() Method
Python string data type provides the join() method which will put given multiple strings into an existing string. The join() method also accepts iterable objects like a list where every item in the list will be converted into a string and then added to the given string. This is more practical than using the for iteration where there is no need to create a loop. But this will work only for the lists only contains string items. If the list contains non-string items it will throw exception.
mylist = [ "1" , "2" , "poftut" , "ahmet"] mystr = "".join(mylist) print(mystr)
Covert List To String Using List Comprehension
The list comprehension is a method used to extract the list items one by one returning them as list again. It is like a loop but we can make operations over the items during the comprehension.
mylist = [ 1 , 2 , "poftut" , "ahmet"] mystr = "".join( [str(x) for x in mylist] ) print(mystr)
Covert List To String Using map() Method
The map() method is similar to the list comprehension where given list items will be iterated and joined as a string by using the join() method. In this case, we will provide the str() method as the first parameter for the map() method in order to convert every item of the mylist.
mylist = [ 1 , 2 , "poftut" , "ahmet"] mystr = "".join( map( str , mylist) ) print(mystr)