Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python find substrings based on a delimiter

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.

like image 992
MAG Avatar asked Sep 15 '13 03:09

MAG


2 Answers

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).

like image 122
Escualo Avatar answered Oct 04 '22 19:10

Escualo


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.

like image 45
DHandle Avatar answered Oct 04 '22 20:10

DHandle