There are the following methods to convert a list to a string in Python.
- Method 1: Using the join() function
- Method 2: Using the map() function
- Method 3: Using the for loop and string concatenation
Method 1: Using the join() function
To convert a list to a string in Python, you can use the join() function. The string join() is a built-in function that takes one parameter, the list, and returns the string by joining all the elements of an iterable, separated by a string separator if provided.
Example 1
data = ["Millie", "Bobby", "Brown", "is", "Enola", "Holmes"]
def listToString(list):
str1 = " "
return (str1.join(list))
convertedStr = listToString(data)
print(convertedStr)
Output
Millie Bobby Brown is Enola Holmes
In this code, we have defined a list and a user-defined function. The listToString() function accepts and passes the list to the join() method. Finally, the join() method is called upon an empty string and returns the string.
Example 2
To convert the list of chars to a string in Python, you can use the join() method.
charList = ["M", "I", "L", "L", "I", "E"]
charStr = ''.join(charList)
print(charStr)
Output
MILLIE
Method 2: Using the map() function
Python map() method executes the specified function for each element in an iterable. The element is sent to the function as a parameter.
Example 1
strList = ["Millie", "Bobby", "Brown", "is", "Enola", "Holmes", 1, 2, 3]
listToStr = ' '.join(map(str, strList))
print(listToStr)
Output
Millie Bobby Brown is Enola Holmes 1 2 3
Example 2
To convert a comma-separated string from the list, use the join() method.
strList = ["Millie", "Bobby", "Brown", "is", "Enola", "Holmes", 1, 2, 3]
listToStr = ','.join(map(str, strList))
print(listToStr)
Output
Millie,Bobby,Brown,is,Enola,Holmes,1,2,3
Method 3: Using the for loop and string concatenation
To convert a list to a string, we can convert each list element to a string. Then we can concatenate them to form a string.
my_list = ['apple', 'banana', 'cherry']
my_string = ''
for element in my_list:
my_string += element + ', '
my_string = my_string[:-2]
print(my_string)
Output
apple, banana, cherry
That’s it.
hello, do you know how to get this result ?
“Millie”,”Bobby”,Brown”,”is”,”Enola”,”Holmes”,1,2,3
The idea is to still see the quotes in the output ?