How To Convert List To String in Python?
Python provides different variable type for programmers usage. We can use int, float, string, list, set … data types in our applications. While using different type of variables we may need to convert then to different types. In this tutorial we will different type of conversion from list to string in Python.
Convert Using Join
One of the most basic usage and implementation to convert list into string is converting list of strings with
join function. Keep in mind that only list that only contains strings can be used with this method. As we can see that each element is delimited with a single space in the new string.
#'a b c'
Convert Different Types Like Integer
As stated before we can convert a list which is only consist of string elements. But what if we need to convert a list which contains different type of data. We need some conversion into string. We will use
str function to convert different data types into string.
mylist = [1, 2, 3]
' '.join(str(e) for e in mylist)
#'1 2 3'
Specify Different Delimiters
Up to now we have provided
space as separator in elements in new string. But we can specify different delimiters by changing
space with new delimiter like
Specify Range To Convert
In some situations we may do not need to convert the whole list into string. In this situations we can specify the range we need to convert. In this example we will only convert first two element in a list. We will define the first two elements with
' '.join(str(e) for e in mylist[:2])