How can you convert a string to a list in Python?
To convert a string into a list, you can use the split() method. This method splits the string into a list of strings, where each word, character, or specified delimiter is considered an element.
Here is an example code of converting a string into a list:
string = "Hello World"
my_list = string.split()
print(my_list)
# Output: ['Hello', 'World']
In the example above, the string “Hello World” is split into a list [‘Hello’, ‘World’] using the split() method. By default, the split() method uses a space as the delimiter, but you can also specify a different delimiter inside the parentheses. For example:
string = "apple,banana,orange"
my_list = string.split(",")
print(my_list)
# Output: ['apple', 'banana', 'orange']
In the above example, the string “apple,banana,orange” is split based on commas and converted into a list [‘apple’, ‘banana’, ‘orange’].