How to Create a List from a String in Python
In Python, it is possible to create a list from a string. This can be achieved by using the split()
method provided by Python strings. Here’s how you can do it:
First, you need to determine how to split the string into separate elements in the list. For example, if you want to split the string at every space, you can use the ' '
space character as the word separator.
Here’s an example that demonstrates the process:
1 | phrase = 'I am going to buy the milk' |
In the above example, the string variable phrase
contains the sentence “I am going to buy the milk.” By using the split(' ')
method, we split the string at every space character, resulting in a list of separate words.
By printing the words
list, the output will be ['I', 'am', 'going', 'to', 'buy', 'the', 'milk']
, where each word in the original string is now an individual element in the list.
By using this technique, you can easily convert a string into a list in Python.
tags: [“Python”, “lists”, “strings”, “split”]