- Convert string to list in Python
- Table of Contents — Convert string to list in Python
- Converting string to list in Python:
- Solution 1: Using Split()
- Syntax:
- Parameters:
- Code to Convert string to list in Python
- Solution 2: Using list()
- Code to Convert string to list in Python:
- Convert string to list in Python — Closing thoughts
- Convert String to List in Python
- Upskill 2x faster with Educative
- Methods of converting a string to a list in Python
- 1. String to List of Strings
- 2. String to List of Characters
- 3. List of Strings to List of Lists
- 4. CSV to List
- 5. A string consisting of Integers to a List of integers
- Conclusion
- References
- Python Convert String to List
- Python Convert String to List
- Python String to List of Characters
Convert string to list in Python
In this short tutorial, find how to convert string to list in Python. We look at all the ways you can achieve this along with their pros and cons.
Table of Contents — Convert string to list in Python
Converting string to list in Python:
Data type conversion or type casting in Python is a very common practice. However, converting string to list in Python is not as simple as converting an int to string or vice versa.
Strings can be converted to lists using list() . We will look at this method below. However, in this method, Python would not know where each item starts and ends, returning a list of characters. Hence, Python provides a few alternate methods which can be used to convert a string to a list.
Solution 1: Using Split()
The split method is used to split a string based on a specified delimiter. Once split, it returns the split string in a list, using this method we can convert string to list in Python.
Syntax:
string.split( delimiter, maxsplit)
Parameters:
- Delimiter — Optional. Specifies the desired delimiter to use when splitting the string. If left empty, whitespaces are considered delimiters.
- Maxsplit — Optional. Specifies how many splits to do.
Code to Convert string to list in Python
str_1 = "Hire the top 1% freelance developers" list_1 = str_1.split() print(list_1) #Output: #['Hire', 'the', 'top', '1%', 'freelance', 'developers']
Note: Since no argument was passed as a delimiter, the string was split on whitespace.
Now let’s take a look at an instance where the delimiter is specified.
str_1 = "Hire-the-top-1%-freelance-developers" list_1 = str_1.split("-") print(list_1) #Output: #['Hire', 'the', 'top', '1%', 'freelance', 'developers']
Solution 2: Using list()
As aforementioned, this method converts a string into a list of characters. Hence this method is not used quite often. I would recommend using this method only if you are certain that the list should contain each character as an item and if the string contains a set of characters or numbers that are not divided by a space. If not, the spaces would also be considered as a character and stored in a list.
Code to Convert string to list in Python:
str_1 = "Hire freelance developers" list_1 = list(str_1.strip(" ")) print(list_1) #Output: ['H', 'i', 'r', 'e', ' ', 'f', 'r', 'e', 'e', 'l', 'a', 'n', 'c', 'e', ' ', 'd', 'e', 'v', 'e', 'l', 'o', 'p', 'e', 'r', 's']
Convert string to list in Python — Closing thoughts
The split() method is the recommended and most common method used to convert string to list in Python. This method does not have any significant cons. On the other hand, the typecast method is not widely recommended and is used only when the requirements are met. However, please feel free to practice both methods to facilitate a better understanding of the concept.
Convert String to List in Python
While programming we may need to convert a string to a list in Python. That could be for any other reason. But, a question arises here, how can we convert a string to different forms of lists?
So, here in this tutorial, we will learn how to convert a string into a list in Python.
Upskill 2x faster with Educative
Supercharge your skillset with Educative Python courses → use code: ASK15 to save 15%
Methods of converting a string to a list in Python
Conversion of a string to a list in Python is a pretty easy job. It can be achieved by following different methods as per our requirements.
Here in this tutorial, we are going to deal with all the methods using which we can convert a string to a list in Python for different cases. Below we have listed all the methods:
- A String to List of Strings
- A String to List of Characters
- List of Strings to List of Lists
- CSV to List
- A string consisting of Integers to a List of integers
Now we are going to discuss each one of the above-mentioned techniques one by one.
1. String to List of Strings
When we need to convert a string to a list in Python containing the constituent strings of the parent string (previously separated by some separator like ‘,’ or space), we use this method to accomplish the task.
For example, say we have a string “Python is great”, and we want a list that would contain only the given names previously separated by spaces, we can get the required list just by splitting the string into parts based on the position of space.
Let us look at an example to understand it better.
#given string string1="Python is great" #printing the string print("Actual String: ",string1) #gives us the type of string1 print("Type of string: ",type(string1)) print("String converted to list :",string1.split()) #prints the list given by split()
- We consider a string, string1=»Python is great» and try to convert the same list of the constituent strings
- type() gives us the type of object passed to the method, which in our case was a string
- split() is used to split a string into a list based on the given separator. In our code, the words were separated by spaces. By default, if we do not pass anything to the split() method it splits up the string based on the position of spaces
- Hence though we have not mentioned the separator parameter, the split() method gives us a list of the respective strings
2. String to List of Characters
What if we need a list of characters present in a string? In that case, direct type conversion from string to list in Python using the list() method does the job for us.
Certainly, if the input string is something like “abcd”, typecasting the string into a list using the list() method gives us a list having the individual characters ‘a’, ‘b’, ‘c’, ‘d’ as its elements. Take a look at the given example code below.
#given string string1="AskPython" #printing the string print("Actual String: ",string1) #confirming the type() print("Type of string: ",type(string1)) #type-casting the string into list using list() print("String converted to list :\n",list(string1))
- Firstly here, we initialize a string, string1 as “AskPython” and print its type using the type() method
- And as we can observe, typecasting the string using the list() method gives us a list of the member characters, as required
3. List of Strings to List of Lists
Here, we are going to see how we can combine both the above methods to convert a string to a list of character lists.
Look at the below-given example carefully,
#Given string string1="This is Python" print("The actual string:",string1) #converting string1 into a list of strings string1=string1.split() #applying list method to the individual elements of the list string1 list1=list(map(list,string1)) #printing the resultant list of lists print("Converted to list of character list :\n",list1)
- In this case, after the initialization of the string string1 , we use the first method and convert it into a list of strings
- That is, at this point string1 is a list of strings given by [ ‘This’, ‘is’, ‘Python’ ]
- Then we apply the list() method to all the elements of the list
- string1. As we saw in our previous case this gives us a list consisting of character lists. Note, mass type-casting was performed using the map() function
4. CSV to List
A CSV( Comma Separated Values) string, as its name suggests is a string consisting of values or data separated by commas.
Let us look at how we can convert the such type of string to a list in Python.
#given string string1="abc,def,ghi" print("Actual CSV String: ",string1) print("Type of string: ",type(string1)) #spliting string1 into list with ',' as the parameter print("CSV converted to list :",string1.split(','))
- Similarly, we initiate by considering a string string1 with various data or values separated by commas(‘,’)
- After printing it and its type() , we proceed by splitting it based on the parameter ‘,’
- This makes the values ‘abc’, ‘def’, and ‘ghi’ the elements of a list. In this way, we were able to extract values from a given CSV
5. A string consisting of Integers to a List of integers
Now we are going to convert a string consisting of only integers separated by some space, comma, etc., to a list with integer elements.
For example, look at the code below,
#string with integers sepated by spaces string1="1 2 3 4 5 6 7 8" print("Actual String containing integers: ",string1) print("Type of string: ",type(string1)) #converting the string into list of strings list1=list(string1.split()) print("Converted string to list : ",list1) #typecasting the individual elements of the string list into integer using the map() method list2=list(map(int,list1)) print("List of integers : ",list2)
- We took a string, string1 as “1 2 3 4 5 6 7 8” and print it and its type() consecutively
- Then we split it using the split() method and store the resultant list into a list, list1. At this point, list1 holds [ ‘1’, ‘2’ , ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’ ] as we can see from the output, as expected
- Now we map the function int() throughout the list, typecasting each one of the elements into integers. And further, we store the typecasted mapped list into list2 and print the same
- As a result, we get a list consisting of the integer elements on which now we can perform arithmetic operations.
Conclusion
That’s all now, this was about converting strings into different lists using various methods. Try to use the one which suits your code and solves your purpose as well as meets up to your requirements. Questions in the comments are appreciated.
References
Python Convert String to List
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
We can convert a string to list in Python using split() function. Python String split() function syntax is:
str.split(sep=None, maxsplit=-1)
Python Convert String to List
Let’s look at a simple example where we want to convert a string to list of words i.e. split it with the separator as white spaces.
s = 'Welcome To JournalDev' print(f'List of Words =')
Output: List of Words =[‘Welcome’, ‘To’, ‘JournalDev’] If you are not familiar with f-prefixed string formatting, please read f-strings in Python If we want to split a string to list based on whitespaces, then we don’t need to provide any separator to the split() function. Also, any leading and trailing whitespaces are trimmed before the string is split into a list of words. So the output will remain same for string s = ‘ Welcome To JournalDev ‘ too. Let’s look at another example where we have CSV data into a string and we will convert it to the list of items.
s = 'Apple,Mango,Banana' print(f'List of Items in CSV =')
Python String to List of Characters
Python String is a sequence of characters. We can convert it to the list of characters using list() built-in function. When converting a string to list of characters, whitespaces are also treated as characters. Also, if there are leading and trailing whitespaces, they are part of the list elements too.
s = 'abc$ # 321 ' print(f'List of Characters =')
Output: List of Characters =[‘a’, ‘b’, ‘c’, ‘$’, ‘ ‘, ‘#’, ‘ ‘, ‘3’, ‘2’, ‘1’, ‘ ‘] If you don’t want the leading and trailing whitespaces to be part of the list, you can use strip() function before converting to the list.
s = ' abc ' print(f'List of Characters =')
Output: List of Characters =[‘a’, ‘b’, ‘c’] That’s all for converting a string to list in Python programming. You can checkout complete python script and more Python examples from our GitHub Repository.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us