In this post, we are going to learn how to convert Python list to string by using practical examples for better understanding.
We will be using a step by step approach so you can have a detailed knowledge of how to convert it with ease.
Let’s not wait anymore for it and just jump right into the practical conversion of Python list to string.
What is Python List to String?
A list in Python consists of a number of items. They can be of same datatype or different like integer, float, string, list, tuple etc.
A string defines a text inside a single or double quotes ( ” ” or ‘ ‘).
It defines the process of converting list in Python to string. We’ll now understand it practically by using proper and easy Python code examples.
Converting Python List To String (Multiple Examples)
We will use the join function to convert list to string in Python. See below examples.
Example 1: Converting List of String Datatype
Its easy to convert a list having items of string datatype. We just have to use the list directly inside the join function. See the below code for complete practical demonstration:
listVal = ['Hey,', 'how', 'are', 'you', 'doing', 'today?'] stringVal = ' '.join(listVal) print( stringVal )
You can see that we have initialized a Python list with some strings. We then have created a new variable.
As you can see in the above code, we first have used the single quotes(can use double quotes as well) in which you can define what to place between each item of the list. It can be a comma( , ), hyphen ( – ), underscore ( _ ) etc. We then have passed the list to join function.
Let’s now see what output we’d get from it. See below:
Output
Hey, how are you doing today?
As you can see that we have successfully converted Python list to string.
Example 2: Converting List of Integer Datatype
Let’s now see how to convert a list to string if the items of list are not string. See below code:
listVal = [ 2, 3, 4, 5, 6, 2 ] stringVal = " ".join( str( item ) for item in listVal ) print( stringVal )
We have a list of integers as you can see in the above code. We’ll first have to convert the datatype of each item of list to string. For that, we have used for loop in which each item will be passed to the string function and will be inserted to the variable using the join function.
Let’s now see what output we’d have after implementing the above code.
Output
2 3 4 5 6 2
As you can see that all these values are now just one string which are stored in the above mentioned variable.
So this is how you can easily convert Python list to string. Hope you like this post. Feel free to ask if you have any questions related to the conversion of list to string in Python. I would be glad to answer all.
Conclusion
As a conclusion of this Python post, hope you now have a clear practical idea of how to convert Python list to string. I would be looking forward at your valuable feedback on this post. Thank you for giving your time to this post.