The Python listing can be converted into string with the aid of the usage of the following methods. Let’s apprehend the following methods.
Method – 1
The given string iterates using for loop and adds its component to string variable.
Example –
# List is converting into string
def convertList(list1):
str = '' # initializing the empty string
for i in list1: #Iterating and adding the list element to the str variable
str += i
return str
list1 = ["Hello"," My", " Name is ","Devansh"] #passing string
print(convertList(list1)) # Printin the converted string value
Output:
Hello My Name is Devansh
Method -2 Using .join() method
We can also use the .join() method to convert the list into string.
Example – 2
# List is converting into string
def convertList(list1):
str = '' # initializing the empty string
return (str.join()) # return string
list1 = ["Hello"," My", " Name is ","Devansh"] #passing string
print(convertList(list1)) # Printin the converted string value
Output:
Hello My Name is Devansh
The above technique is not advocated when a list includes both string and integer as its element. Use the adding component to string variable in such scenario.
Method – 3
Using list comprehension
# Converting list into string using list comprehension
list1 = ["Peter", 18, "John", 20, "Dhanuska",26]
convertList = ' '.join([str(e) for e in list1]) #List comprehension
print(convertList)
Output:
Peter 18 John 20 Dhanuska 26
Method – 4
Using map()
# Converting list into string using list comprehension
list1 = ["Peter", 18, "John", 20, "Dhanuska",26]
convertList = ' '.join(map(str,list1)) # using map funtion
print(convertList)
Output:
Peter 18 John 20 Dhanuska 26
Leave a Review