I am new to Python, so I might be missing something simple.
I am given an example:
string = "The , world , is , a , happy , place "
I have to create substrings separated by ,
and print them and process instances separately.
That means in this example I should be able to print
The
world
is
a
happy
place
What approach can I take? I was trying to use the string find functionality, but
Str[0: Str.find(",") ]
does not help in finding 2nd, 3rd instances.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With