A list in Python is used to hold multiple data items, which can be of different data types. It can be
Lists can be converted to strings using some techniques. In this shot, we will learn three different ways of doing this.
Create an empty string, iterate over the items in the list using their index, and then add each iterated item of the list to the empty string.
In the code below, the list alist
was looped through with each item added to the initially empty string strings
. The function convert()
handles this looping, and at the end of the code, the function is called and its output is printed to the screen.
# Function that handles the conversiondef convert(alist):# the empty string is declared and initializedstrings = " "# loop through the list itemfor items in alist:strings += items# return the new stringreturn strings# call the convert functionalist = ['Edpresso ','byte ', 'sized ', 'shots ']print(convert(alist))
In this second method, two Python functions, join()
and map()
, were combined to achieve our conversion.
In the below code snippet, the map()
function iteratively maps each item in the list alist
and readies them for insertion into a string. The join()
function will now join the string object returned by the map function to the empty strings
variable already declared.
The converted string is saved in alistConv
and printed to the screen.
# a list is definedalist = ['Edpresso ', 9 ,'ice','platform',4 ,'byte ', 'sized ', 'shots ']# an empty string is initializedstrings = ' '# alistConv variable saves the outputalistConv = strings.join(map(str, alist))# print result to screenprint(alistConv)
In this method, the join()
function will be used alone without map()
. This contrasts with method 2, where the map()
function served as the iterator. Here, a function that returns the converted code will be used.
# Function that handles the conversiondef liststr(somelist):# the empty string is declared and initializedstrings = " "# return the new stringreturn strings.join(somelist)# call the convert functionsomelist = ['Edpresso ','byte ', 'sized ', 'shots ']print(liststr(somelist))
In this last code example, the join()
function performs a join operation on the items in the list by removing the items from the quotation marks and returning the space-separated list items in the empty string variable created earlier.
And with that, we have three simple and easy list to string conversion methods.