-1

I've got a random bunch of words and I need to make it into a list, but there is a problem, I must take the words as they are and convert them into a list in the program itself. for example I got this raw input:

hello,mike,cat,dog,burger

Now how do i take this 5 words and make my program to make each word into a proper string like so: "hello","mike","cat","dog","burger"

2 Answers 2

6

You can use the split method

>>> s = "hello,mike,cat,dog,burger"
>>> l = s.split(',')
>>> l
['hello', 'mike', 'cat', 'dog', 'burger']
1
  • 1
    Maybe worth mentioning l = [item.strip() for item in s.split(',')] in case of spaces after the coma? Aug 25, 2014 at 19:38
3

You're looking for str.split

the_string = '"hello","mike","cat","dog","burger"'
the_list = the_string.split(",") # split on a literal comma

Note that this requires that the user properly format the string, and that there are no leading or trailing spaces (e.g. Hello, dog becomes ["Hello", " dog"]). Consider building some sanity tests for the string, and possibly mapping the whole thing through str.strip

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.