This post explains how to convert a string to a list in Python.
If you need a list of words in the given string, use the built-in
method on the string. For example:
>>> "this is a test".split() ['this', 'is', 'a', 'test']
If the words are separated by a specific character, you can give that
character as an argument to
>>> "yet,another,example".split(",") ['yet', 'another', 'example']
If you need to do something with each word, use a
for loop like this:
>>> sentence = "this is an example" >>> for word in sentence.split(): ... print(word) ... this is an example
We have written more about how to split a string in a different post.
Sometimes, you need a list where each element is a letter from your string. In
this case, use the
list() built-in function:
>>> list("abc") ['a', 'b', 'c']
The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!