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.
1 2 3 |
my_string = 'This is a string.' my_list = my_string.split() print(my_list) |
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.
1 2 3 4 5 6 7 |
my_string = 'Just a string.' my_list = [] for my_elem in my_string: my_list.append(my_elem) print(my_list) |
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.
1 2 3 |
my_string = 'String,separated,by,commas.' my_list = my_string.split(',') print(my_list) |
Result:
['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.
1 2 3 4 5 6 7 8 9 10 11 |
my_string = 'Actual temperature is 17.' my_list = my_string.split() new_list = [] for my_elem in my_list: if my_elem.isdigit(): new_list.append(int(my_elem)) else: new_list.append(my_elem) print(new_list) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
my_string = 'Actual temperature is -17' my_list = my_string.split() new_list = [] for my_elem in my_list: temp_var = my_elem if my_elem[0] == '-': my_elem = my_elem[1:] if my_elem.isdigit(): new_list.append(int(temp_var)) else: new_list.append(temp_var) print(new_list) |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
my_string = 'Actual temperature is -17' my_list = my_string.split() new_list = [] def IsInt(s): try: int(s) return True except ValueError: return False for my_elem in my_list: if IsInt(my_elem): new_list.append(int(my_elem)) else: new_list.append(my_elem) print(new_list) |
Now, the code is much cleaner and the returned list is the same for both: negative and positive numbers.