Convert String to List [Array]

If you want to convert a string to a list, you have a bunch of options; you can do it for entire sentences, words, or characters.

In this lesson, I’ll show you how you can do this using a few different approaches.

Split string into words

The first way to convert a string to a list, so it contains words as elements, is to split it by spaces.

The split function takes an optional parameter, which is a separator by which a string is split into smaller chunks. By default, it uses space as a separator, so we don’t need to add it explicitly.

If you run the code, you’ll get words as a list of elements.

['This', 'is', 'a', 'string.']

Split string into a list of characters

If you like to convert a string to a list of characters, you can use the for loop.

First, we created an empty list. In the for loop, each string element (character) is appended to the end of the list. The whole string is therefore converted to a list.

If you run the code, you’ll get this result.

['J', 'u', 's', 't', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', '.']

In the previous example, I wrote that the split function takes an additional parameter – the separator. If you want to change it from space to comma, you have to do it explicitly.


['String', 'separated', 'by', 'commas.']

Convert String Elements to Ints if Possible

If your string contains integer values, which you want to convert into list elements, but keep the type if possible, you have to recognize them first, and then cast them to int.

If you print new_list to the console, you will notice that all elements but the last one are strings.

['Actual', 'temperature', 'is', 17]

So far so good. But try to change 17 to -17.

['Actual', 'temperature', 'is', '-17']

The negative number is still written as a string. We could remove the negative number and then try to check if the value is int. But there is another problem. Some words that are not integers can contain “-“.

One method to deal with it is to create a temporary variable where remove “-” from the beginning, and if then the value is still a digit, we know that we deal with a negative number.

First, the function checks whether the first character in the word is “-“. If it is the case, it tries to check whether the value is a digit. If the condition is met it cast the negative number to int.

Now, the code works for both positive and negative numbers.

['Actual', 'temperature', 'is', -17]

This approach is probably not very elegant. We can do it differently.

First, let’s create a function that will try to convert the value to int. If it fails, it will return false, if it succeeds, it will return true, and then we know that the value can be converted to int.

Now, the code is much cleaner and the returned list is the same for both: negative and positive numbers.