Python program to convert string to a List

In this program, we will try to convert a given string to a list, where spaces or any other special characters, according to the users choice, are encountered. To do this we use the split() method.

Converting a string to a list in Python can be done using several methods, including the split() method, the list() constructor, and using list comprehension.

Using the split() method:

The split() method splits a string into a list of substrings based on a specified separator. The separator can be a space, comma, or any other character. 

 

string = "hello world"
lst = string.split()
print(lst)

Output: ['hello', 'world']

Using the list() constructor:

The list() constructor converts any iterable object, including a string, to a list. 

 

string = "hello world"
lst = list(string)
print(lst)

Output: ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

Using list comprehension:

List comprehension is a concise way to create a list based on an existing iterable object. 

 

string = "hello world"
lst = [char for char in string]
print(lst)

Output: ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']

All three methods achieve the same result of converting a string to a list in Python. The choice of method depends on the specific requirements and preferences of the programmer.

Submit Your Programming Assignment Details