How To Convert List To String in Python? – POFTUT

How To Convert List To String in Python?


Python provides different variable types for programmers’ usage. We can use int, float, string, list, set … data types in our applications. While using different types of variables we may need to convert them to different types. In this tutorial, we will different types of conversion from the list to string in Python.

Convert Using Join

One of the most basic usage and implementation to convert a list into a string is converting a list of strings with join() function. Keep in mind that only a 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.

mylist=['a','b','c'] 
' '.join(mylist) 

#Output
#'a b c'

Convert Different Types Like Integer

As stated before we can convert a list which only consists of string elements. But what if we need to convert a list which contains a different type of data. We need some conversion into a string. We will use the str() function to convert different data types into a 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 a separator in elements in a new string. But we can specify different delimiters by changing space with a new delimiter like , command.

mylist=['a','b','c']                                                                                             
','.join(mylist)

#Output 
#'a,b,c'

Specify Range To Convert

In some situations, we may do not need to convert the whole list into a string. In these situations, we can specify the range we need to convert. In this example, we will only convert the first two-element in a list. We will define the first two elements with [0:2]

mylist=['a','b','c']                                                                                             
' '.join(str(e) for e in mylist[0:2])                                                                            
#Output
#'a b'

LEARN MORE  Linux Bash Shell Printf Command Examples

Leave a Comment