In this tutorial, we will outline how to convert a list into a string in Python. This is a common task in Python programming, and understanding how to perform it will greatly enhance your productivity when dealing with lists and strings.
Python provides several methods to do this conversion, and we will look at a few of them: str.join, list comprehension and map function.
Benefit
There is often a need to convert a list to a string format for display, saving into a file, or sending it over the network. This can easily be achieved by using the built-in Python methods.
Method 1: Using str.join
The simplest and most common method to convert a list into a string in Python is using the built-in str.join() method. This method combines all the elements in a list into a single string. If you want the items in your list to be separated by a specific character or string, you can specify this as the argument in the str.join() method.
In this example, the string is created by connecting each item with a comma.
1 2 3 |
list1 = ['Hello', 'world', 'Python', 'is', 'great!'] str1 = ', '.join(list1) print(str1) |
Method 2: Using List Comprehension
Another way to convert a list to a string in Python is by using list comprehension which provides a concise way to create lists. In this case we will use it to convert each item in the list to a string.
Example:
1 2 3 |
list1 = [1, 2, 3, 4, 5] str1 = ''.join([str(i) for i in list1]) print(str1) |
Method 3: Using map Function
The map function in Python applies a specific function to every item in an iterable object (like a list). Here, we use the map function to apply the str function to every item in the list.
Example:
1 2 3 |
list1 = [1, 2, 3, 4, 5] str1 = ''.join(map(str,list1)) print(str1) |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#Using str.join list1 = ['Hello', 'world', 'Python', 'is', 'great!'] str1 = ', '.join(list1) print(str1) #Using List Comprehension list1 = [1, 2, 3, 4, 5] str1 = ''.join([str(i) for i in list1]) print(str1) #Using map Function list1 = [1, 2, 3, 4, 5] str1 = ''.join(map(str,list1)) print(str1) |
Output
Hello, world, Python, is, great! 12345 12345
Conclusion
Converting a list into a string is a common operation in Python and can be done in different ways. The method you choose will depend on your requirement. Remember, efficient use of these methods can significantly increase your productivity and make your Python code more readable and maintainable.