Convert a List to a space-separated string in Python

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.

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top