Thought leadership from the most innovative tech companies, all in one place.

How to convert list to string in Python

In this post, we will go over how to convert a list to a string in Python.

image

Short Answer

The easiest way to do this is to use .join():

list1 = ['1', '2', '3', '4', '5']
str1 = ''.join(list1)
print(str1)
# 12345

In the ''.join() , you can change to use different separators like '\t'.join() or ','.join() .

Why

Let us check out the list definition in Python first. List is a collection that includes ordered and mutable elements. The elements in the list can be the same or different types. Also, the list can be an item in the Pandas DataFrame. In Python list is written down in square brackets [].

In real application, things can be much complicated when you start to analyze raw data.

List with string

If the list only has one data type as str, you can use the join function to satisfy your need.

List with multiple data types

list1 = [1, 2, 12, 6, ‘ABC’]

If you use the .join() function, it will never work. You will receive an error:

TypeError: sequence item 0: expected str instance, int found

You have to cast the integer into a string then use the .join() function to finish the work. There are two ways to do:

list1 = [1, 2, 12, 6, 'ABC']

str1 = ','.join([str(x) for x in list1])

str2 = ', '.join(map(str, list1))

# '1,2,12,6,ABC'

List to String in Pandas DataFrame

When you are manipulating the list in the Pandas dataframe, things can be a little bit annoying.

For example,

# initialize list of lists

data = [['tom', ['comment1', 'comment2']], ['nick', ['comment3', 'comment4']], ['juli', []]]

# Create the pandas DataFrame

df = pd.DataFrame(data, columns = ['Name', 'Comments'])


    Name 	        Comments
-------------------------------------
0   tom		['comment1', 'comment2']
-------------------------------------
1	nick	['comment3', 'comment4']
-------------------------------------
2	juli	[]

To convert the ‘Comments’ column into a single string, you can use the .apply in the Pandas.

df['new_comments'] =  df['Comments'].apply('. '.join)

	Name		   Comments				 new_comments
----------------------------------------------------------
0	tom		['comment1', 'comment2']	comment1. comment2
----------------------------------------------------------
1	nick	['comment3', 'comment4']	comment3. comment4
----------------------------------------------------------
2	juli	[]



Continue Learning