[Tutor] Getting started with Python

Charlie Clark charlie@begeistert.org
Thu, 23 May 2002 14:16:34 +0000


>From one Charlie to another!

Let's try taking your message as an example

>>> s = """I am trying to search a text file with a specified string,and i 
am having trouble doing it.
I tried with re, and having lots of trouble
for example if a text contain strings "abc" it will print out all the 
string starting with abc.

Can you give me some hint on doing this in Python"""
>>> s.find("abc")
180
# this means abc occurs at the 181st position in the string

>>> print s[180:]
abc" it will print out all the string starting with abc.

Can you give me some hint on doing this in Python. 

You could easily put this in a loop

>>> while 1:
...     start = s.find("abc")
...     if start > -1:
...             print s[start:]
...             s = s[start + 3:]
...     else:
...             break
...
abc" it will print out all the string starting with abc.
abc. 

But maybe you just want the word containing the text abc? In this case you 
would have to start looking for spaces to the left and right of "abc" and 
what would do with quotes and stuff? If you need some more intelligence 
than the above example then you should probably use regular expressions. 
But you should be able to plug them into the above loop.

Charlie