Convert string to list Python
In this post, you will learn different ways to convert a string to a list using the Python programming language.
In the development process, we may face some scenario where there may need to be performed a data conversion operation. In Python, List is a mostly used data structure, it contains any type of data objects with a comma separated and enclosed within a square bracket. A single list may contain data types like Integers, Strings, as well as Objects or even another list inside a list. In Python, a string is used for representing characters. Strings are immutable, indexable, iterable. There are several ways to convert a string to a list, like using split() method.
Using split() method
We can convert a string to a list using Python's inbuilt split() method. This method splits a string and stores them in the list. The syntax of split() method is -
string.split(separator, maxsplit)
You can specify the separator, the default separator is any white space. The maxsplit is optional, it specifies how many splits to do.
Example1: Convert string to list
Here is the simple example where we convert a string to a list of words with the separator as white spaces.
str1 = 'Welcome To EtutorialsPoint'
print(f'List of Words ={str1.split()}')
Output of the above code -
List of Words =['Welcome', 'To', 'EtutorialsPoint']
Example2: Convert string to list
In the given example, we split a string into a list on the basis of the given separator.
x_str = 'Welcome-To-EtutorialsPoint'
x_list = list(x_str.split("-"))
print("List of Words = ",x_list)
Output of the above code -
List of Words =['Welcome', 'To', 'EtutorialsPoint']
Convert string to list of character
Python string is a sequence of characters. We can convert a string to a list of characters using Python's inbuilt list() function. While converting, all whitespaces are also treated as characters. Here is an example to demonstrate this -
str1 = 'Welcome To EtutorialsPoint'
print(f'List of Words ={list(s)}')
Output of the above code -
List of Words =['W', 'e', 'l', 'c', 'o', 'm', 'e', ' ', 'T', 'o', ' ', 'E', 't', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'P', 'o', 'i', 'n', 't']
We can remove the leading and trailing whitespaces using Python inbuilt strip() method -
str1 = ' etutorialspoint '
print(f'List of Words ={list(str1.strip())}')
Output of the above code -
List of Words =['e', 't', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't']
Related Articles
Convert list to dictionary Python
Convert array to list Python
numpy dot product
glob in Python
Python heap implementation
zip function in Python
Remove last element from list Python
Check if list is empty Python
Remove element from list Python
Split with multiple delimiters Python
Python loop through list
Python iterate list with index
Python add list to list
Python random choice
Dictionary inside list python
Remove character from string Python
Python raise keyword