How to Convert a List into a String in Python 


               


How to Convert a List into a String in Python



Python


In this article, we show how to convert a list into a string in Python.

So let's say that we have a list of elements in Python. However, we want to convert this list of elements into a string.

We can do this in Python with the join() function.

With the join() function, we can join the elements in a list with any type of character, such as with whitespace, a comma, semicolon, etc.

We simply have to specify this character(s) with the join() function.

We show this in the following code below.



So we have a variable, list1, which is set equal to, ['He', 'went', 'to', 'the','store']

It's just an example.

In the first example, we have the line, string1= ' '.join(list1)

This joins all of the elements of the list with a whitespace in between them. This gives us the output, 'He went to the store'

In the next example, we have an empty string (no spaces) as the parameter. This gives us the output, 'Hewenttothestore'

In the next example, we have the string separated by commas. This gives us the output, 'He,went,to,the,store'

In the next example, we have '123 ' separate each item in the string. This gives us the output, 'He123 went123 to123 the123 store'

And in the last example, we have commas in separating the elements of the list in the string. This gives us the output, 'He;went;to;the;store'

And this is how we can convert a list into a string in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...