Let's say you had a string
test = 'wow, hello, how, are, you, doing'
and you wanted
full_list = ['wow','hello','how','are','you','doing']
i know you would start out with an empty list:
empty_list = []
and would create a for loop to append the items into a list
i'm just confused on how to go about this,
I was trying something along the lines of:
for i in test:
if i == ',':
then I get stuck . . .
asked Aug 27, 2012 at 2:54
O.rka
31.1k78 gold badges213 silver badges336 bronze badges
-
This is a dupe: stackoverflow.com/questions/5453026/string-to-list-in-pythonMatthew Trevor– Matthew Trevor2012年08月27日 03:19:34 +00:00Commented Aug 27, 2012 at 3:19
-
Upvotes for a question already asked a dozen times without having done any research?user2665694– user26656942012年08月27日 03:22:07 +00:00Commented Aug 27, 2012 at 3:22
2 Answers 2
In Python, the nicest way to do what you want is
full_list = test.split(', ')
If your string might have some commas that aren't followed by spaces, you would need to do something a little more robust. Maybe
full_list = [x.lstrip() for x in test.split(',')]
Sign up to request clarification or add additional context in comments.
1 Comment
minopret
Perhaps tack .lstrip() on the end to remove the spaces that follow the commas.
>>> test = 'wow, hello, how, are, you, doing'
>>> full_list = test.replace(",","','")
>>> print full_list
wow',' hello',' how',' are',' you',' doing
i just added the flanking quotations manually
answered Aug 27, 2012 at 6:22
O.rka
31.1k78 gold badges213 silver badges336 bronze badges
2 Comments
John La Rooy
This is a string that looks a bit like the string representation of a list. A list is a very different thing to a string
Pierre GM
Agreeing w/ @gnibbler : this answer has little to do with the question, -1.
lang-py