The join function is one of the simplest methods to convert a list to a string in python. The main point to keep in mind while using this function is that the join function can convert only those lists into string that contains only string as its elements.
list=['hello', 'how', 'are', 'you']
print(list) # this will print the list
str=' '.join(list)
print(str)
'hello how are you' # this is a string
Now, there may be cases where a list will contain elements of data type other than string. In such cases ,the join function can not be used directly. For a cases, like these, str() function will first be used to convert the other data type into a string and then further, the join function will be applied.
list=['1','2','3']
str1=' '.join (str(e) for e in list)
print(str1) # this will print a string
No comments:
Post a Comment