In this short tutorial we will learn how to use the Python string split function to convert single or multiple row strings into list objects which you are able to use for further Data Analysis or automation tasks.
Convert string to list of elements in Python
Consider the very simple string made of the following words:
lang_str = "Python, R, Julia, Haskell"
The easiest way to turn the string into the list of words in Python is, as mentioned before, using the split function.
The result will be:
['Python', ' R', ' Julia', ' Haskell']
Convert string list to int list
In the following example we would like to cast a string of numbers to a list of integers. Consider the folllowing string:
number_str = "345,435,536,678.9"
As we learnt before, we can use the split function with the comma delimiter to create a list of strings:
number_lst = number_str.split(',') print(number_lst)
The result is a list of strings:
['345', '435', '536', '678.9']
Trying to cast each element of the list to int directly using a comprehension won’t work. We’ll receive the following error as the last element has decimal numbers.
ValueError: invalid literal for int() with base 10
Casting to float and then convert to int will do the trick here:
int_lst = [int(float(x)) for x in number_lst] print(int_lst)
[345, 435, 536, 678]
Convert a string to a list of its characters
Our last example for today is how to simply split a strings to a list of its characters.
Consider the string below:
lang_str = 'Python,R'
The simplest way to divide this string to its characters is to call the list() constructor:
['P', 'y', 't', 'h', 'o', 'n', ',', ' ', 'R']
You can use a list comprehension as well:
char_lst = [lang_str[x] for x in range(len(lang_str))]
Both methods will render the same output.