Overview
As a programmer, you might come across scenarios where you have to convert a string into a list. Now, your requirements might vary, depending on the goal of your program. For example:
Example 1: Given a string containing words; how to extract each word of the string and store them as individual items in a list.? In other words, converting a given string to a list of strings.
text = "Learning Python Is Awesome!"
Output:
List: ['Learning', 'Python', 'Is', 'Awesome!']
Example 2: Given a string separated with commas; how to store the items in a list?
Given String:
text = "Rock,Brock,John"
Output:
List: ['Rock', 'Brock', 'John']
Example 3: Given a string; how to extract each character of the string? In other words, converting a string to a list of characters.
Given String:
text = "AEIOU"
Output:
['A', 'E', 'I', 'O', 'U']
Example 4: Given an Integer string; how to convert it to a list of integers?
Given String:
ip = "192.168.10.1"
Output:
List of integers : [192, 168, 10, 1]
Example 5: Given a string; how to convert it to a list of lists?
Given String:
text = ['Apple','Mango', 'Banana', 'Orange','Cherry']
Output:
[['Apple'], ['Mango'], ['Banana'], ['Orange'], ['Cherry']]
In this article, we are going to see, how we can solve the above-mentioned scenarios and convert a string to a list in Python. So, without further delay let us dive into the solutions one by one.
❖ Converting a String To a List of Strings Using split() Method
split()
is a built-in method in Python which is used to split a string into a list.
Syntax
string.split(separator, maxsplit)
Parameter | Optional/Mandatory | Default Value | Description |
separator | Optional | Whitespace | Represents the separator to be used while splitting the string. |
maxsplit | Optional | -1 | Used to specify how many splits to be done. |
Example:
text = "Learning Python Is Awesome!" li_text = text.split(' ') print("List:",li_text)
Output:
List: ['Learning', 'Python', 'Is', 'Awesome!']
❖ Converting a String With Comma Delimited Items To a List
◆ Using split()
To separate a string that contains items separated by commas as shown in the example below we can again use the split()
function by passing a comma in the separator argument.
Example:
text = "Rock,Brock,John" li_text = text.split(',') print("List:",li_text)
Output:
List: ['Rock', 'Brock', 'John']
◆ Using a Custom Function
We can also define a custom function to split our string and append the items one by one to a list. Let us have a look at how we can do that use ou function in the program given below.
text = "Rock,Brock,Jhon" def convert(a): count = 0 li = [] li_text = "" for i in a: count = count+1 if i != ',': li_text = li_text+i if count == len(text): li.append(li_text) else: li.append(li_text) li_text = "" print("List:",li) convert(text)
Output:
List: ['Rock', 'Brock', 'Jhon']
❖ Converting a String To A List of Characters Using list() Method
To convert a given string to a list of characters, we can simply convert or type cast the given string to a list using the list() method.
➥ The list()
is used to return a list in Python. Therefore it can be used to typecast a given sequence like a string to the list type.
Let us have a look at how we can typecast the string into a list of characters in the program given below.
text = "AEIOU" print(list(text))
Output:
['A', 'E', 'I', 'O', 'U']
❖ Convert an Integer String To a List of Integers
To convert a string containing integers as strings, we need to use a combination of the split()
method, list()
method and the map()
methods in Python. We already discussed the usage of the list()
and split()
methods in the above examples; let understand the usage of the map()
method.
➥ The map() Method
With Python’s map() function, you can apply a specific function to each element of an iterable.
It takes two arguments:
- Function: Often it’s a lambda function that you can define on the fly. This is the function which you are going to apply to each element of an iterable.
- Iterable: This is the iterable which you convert into a new iterable where each element is the result of the applied map() function.
The result is a map() object.
For further details on the map() method, please follow our blog tutorial at this link.
Now that we know how to use the list()
and the map()
methods, let us apply them and convert the given string into a list.
ip = "192.168.10.1" li=list(ip.split('.')) li_int=list(map(int,li)) print("List of integers: ",li_int)
Output:
List of integers : [192, 168, 10, 1]
In the above program:
- We split the string using the
split()
method with . as the separator. - We then typecast our string and store it in a list using the
list()
function. The list at this point looks like this : [‘192’, ‘168’, ’10’, ‘1’] - Therefore, we use the
map()
function to map theint()
function through each item in the list and convert each element to an integer. Finally, we display the typecasted integer values as an output. Since these values are integers, we can also perform arithmetic operations on them.
❖ Converting a List Of Strings To a List of Lists
If the given list contains strings that do not have any complications then the split()
method is the only weapon we need to convert it to a list of lists containing strings. Let us quickly have a look at that in the example given below.
text = ['Apple','Mango', 'Banana', 'Orange','Cherry'] print("ORIGINAL LIST: ") print(text) print("LIST OF LISTS: ") li = [i.split(",") for i in text] print(li)
Output:
ORIGINAL LIST: ['Apple', 'Mango', 'Banana', 'Orange', 'Cherry'] LIST OF LISTS: [['Apple'], ['Mango'], ['Banana'], ['Orange'], ['Cherry']]
However, what if the given string is something like the one given below! It won’t lead us to the correct output because in this case, we not only need to separate the strings but also eliminate the extra brackets.
Given String:
text = ["[10,20]", "[30,40]"]
Expected Output:
[['10', '20'], ['30', '40']]
To solve the above problem we can use couple of approaches. Let us discuss them.
◆ Method 1: Using strip() and split() Methods
string.strip()
: Built-in method in Python that removes leading and trailing whitespaces including newline characters ‘\n’ and tabular characters ‘\t’.
Optional argument: string.strip(characters)
. This will remove specific characters from the left and the right of the string.
For more details please refer to our blog tutorial here.
We are going to use the strip()
method to eliminate the brackets while the split()
method is used to make the data in the list of lists comma-separated. Let us have a look at this in the program given below:
text = ["[10,20]", "[30,40]"] print("ORIGINAL LIST: ") print(text) print("LIST OF LISTS: ") li = [i.strip("[]").split(",") for i in text] print(str(li))
Output:
ORIGINAL LIST: ['[10,20]', '[30,40]'] LIST OF LISTS: [['10', '20'], ['30', '40']]
◆ Method 2: Using List Slicing
Instead of stripping the brackets, we can slice the given list from the second element to the second last element which enables us to eliminate the brackets. The task and logic behind the program are the same, we just changed our approach of eliminating the brackets. So, let us have a look at how we can do it.
text = ["[10,20]", "[30,40]"] print("ORIGINAL LIST: ") print(text) print("LIST OF LISTS: ") li = [i[1:-1].split(",") for i in text] print(str(li))
Output:
ORIGINAL LIST: ['[10,20]', '[30,40]'] LIST OF LISTS: [['10', '20'], ['30', '40']]
Note: Based on the given string, you might have to adjust the slice. To learn about slicing, please follow our blog tutorial here.
Conclusion
In this article, we learned how to Convert a String To a List In Python using numerous methods and scenarios. After reading this article, I hope you can easily convert strings to lists in Python. You might want to have a look at this article: How To Split A String And Keep The Separators? if you want to further sharpen your skills with the split()
method.
Please subscribe and stay tuned for more articles!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.