How to split a string into a list array in Python?

In today’s tutorial we will learn how to manipulate strings and divide them into arrays, typically referred as list objects in Python. You might need to do this exercise quite often if reading textual information from text or csv files into list of strings or numbers.

SPlit string by comma or other delimiter

We use the string split() function in order to cut our string into smaller chunks.

Assume that you have the following list:

data_str = 'Python, Excel, Power BI, R, Tableau'

Dividing the string by commas in easy:

del_char = ','
data_lst = data_str.split(del_char)
print(data_lst)

You will get the following list:

['Python', ' Excel', ' Power BI', ' R', ' Tableau']

Important note: A common beginner method is to try to divide a list using split(), this will result in an Attribute error, as lists do not have a split method.

Divide string by space character

In the same fashion we can use the space character as the delimiter:

data_str = 'Python Excel Power BI R Tableau'
del_char = ' '
data_lst = data_str.split(del_char)
print(data_lst)

This return the following array:

['Python', 'Excel', 'Power', 'BI', 'R', 'Tableau']

Convert string into char array

Next case we will handle is to convert a string to an array of its characters:


data_str = 'Python Excel'
#Using the list constructor function
list(data_str)

This return the following array of characters:

['P', 'y', 't', 'h', 'o', 'n', ' ', 'E', 'x', 'c', 'e', 'l']

Split string by multiple delimiters

What if we have several possible delimiting characters? We’ll define the delimiters as a list and loop:

data_str = 'Python,Excel,Power-BI R Tableau'
del_lst = [',', ' ']

for del_char in del_lst:
    print('String divided by delimiter {}: '.format(del_char) + str( data_str.split(del_char)))

This will return the following:

String divided by delimiter ,: ['Python', 'Excel', 'Power-BI R Tableau']
String divided by delimiter  : ['Python,Excel,Power-BI', 'R', 'Tableau']