When you are coding your program in python, we have to convert the list to string many times. Are there any short methods to convert list to string in python? Yes, today in this tutorial you will go through different methods for the python program to convert list to string. Choose one of your best methods and use it in your program to make it more compatible and easy to implement. Here are some examples of conversion of the python program to convert list to string
Input: ['Python', 'program', 'to', 'convert', 'list', 'to', 'string'] Output: Python program to convert list to string
Input: ['I', 'am', 'learning', 'python', 'programming'] Output: I am learning python programming |
Now, let's see various methods of converting the list to string in python.
First create a function to convert a list to string.
Now create a string that is empty. Also, get the traverse in the string.
Return the string and print the output
# Python program to convert a list to string
# Create a Function to convert |
Programinpython
Method 2- Using .join() function
First create a function to convert a list to string.
Now create an empty string.
Return the string and use join() method.
Initialize input and print the output
# Python program to convert a list to string using .join()
# Create a Function to convert a list |
python list to string
Method 3- By using List Comprehension
Initialize a list in a variable.
Use list comprehension and .join() method.
Print the output
# Python program to convert a list to string by using list comprehension
s = ['I', 'am', 'a', 'python', 'programmer']
# using list comprehension listToStr = ' '.join([str(elem) for elem in s])
print(listToStr) |
I am a python programmer
Method 4- By using map() function
Initialize a list.
Use list comprehension, .join (), .map() method.
Print the output
# Python program to convert a list to string using map() and list comprehension
s = ['Python', 'is', 'a', 'programming', 'language']
# Now use list comprehension and .map() function listToStr = ' '.join(map(str, s))
print(listToStr) |
Article Contributed By :
|
|
|
|
1081 Views |