I am new to Python, so I might be missing something simple.
I am given an example:
string = \"The , world , is , a , happy , place \"
Simple thanks to the convenient string methods in Python:
print "\n".join(token.strip() for token in string.split(","))
Output:
The
world
is
a
happy
place
By the way, the word string
is a bad choice for variable name (there is an string
module in Python).
Strings have a split()
method for this. It returns a list:
>>> string = "The , world , is , a , happy , place "
>>> string.split(' , ')
['The', 'world', 'is', 'a', 'happy', 'place ']
As you can see, there is a trailing space on the last string. A nicer way to split this kind of string would be this:
>>> [substring.strip() for substring in string.split(',')]
['The', 'world', 'is', 'a', 'happy', 'place']
.strip()
strips whitespace off the ends of a string.
Use a for
loop to print the words.
Another option:
import re
string = "The , world , is , a , happy , place "
match = re.findall(r'[^\s,]+', string)
for m in match:
print m
Output
The
world
is
a
happy
place
See a demo
You could also just use match = re.findall(r'\w+', string)
and you will get the same output.
Try using the split
function.
In your example:
string = "The , world , is , a , happy , place "
array = string.split(",")
for word in array:
print word
Your approach failed because you indexed it to yield the string from beginning until the first ",". This could work if you then index it from that first "," to the next "," and iterate across the string that way. Split would work out much better though.