This tutorial will discuss about unique ways to convert a list to a space-separated string in Python.
Table Of Contents
Method 1: Using join() method
String has a function join()
. It accepts a sequence of strings as an argument, then joins all the strings in that sequence, and returns the joined string. The string object, through which join()
method is called, will be used as separator while joining the strings.
So, to convert a List of strings into a space-separated string, call the join()
method on a string containing a whitespace only. Also, pass the list of strings as argument in it. It will join all the strings in list into a space-separated string and returns it.
Let’s see the complete example,
listOfStrs = ['This', 'is', 'a', 'sample', 'string'] # Convert a list to a space-separated string strValue = ' '.join(listOfStrs) print(strValue)
Output
This is a sample string
It converted a list of strings into a pace-separated string.
Frequently Asked:
- Python: check if two lists are equal or not ( covers both Ordered & Unordered lists)
- Print all items in a List with a delimiter in Python
- Convert a number to a list of integers in Python
- Convert a List of strings to a List of Integers in Python
Method 2: Using map() method
In the previous example, we converted a list of strings into a space-separated string. but if list does not have only string elements? What if list has few integers too?
In that case, first we need to convert the type of all elements of list into string type, and then using join()
method, we can join them into a space-separated string.
Let’s see the complete example,
listOfStrs = ['This', 'is', 10, 'sample', 'string'] # Convert a list to a space-separated string strValue = ' '.join(map(str, listOfStrs)) print(strValue)
Output
This is 10 sample string
It converted a list into a space-separated string.
Summary
We learned about different ways to convert a list into a space-separated string in Python. Thanks.