Find the ID, but how to select/copy the whole string by ID?

Francesco Guerrieri f.guerrieri at gmail.com
Wed Sep 19 10:41:43 EDT 2007


On 9/19/07, Leon <mingliang2000 at gmail.com> wrote:
> stringID = str(raw_input('Enter the string ID : '))
> file = open('strings.txt')
> sourcefile = file.read()
> file.close()
> sourcefile.find (stringID)
>
> but how can I select and copy the specific string from <str> to </str>
> with id I input?

If the file you are parsing is in xml, there are many parser out there
which can help you (this is discussed very often on this list, even
today) .

If the format is very simple and you really want to do it by hand, you
could do something like:

stringID = raw_input('Enter the string ID:')
for line in open('strings.txt'):
    if line.find(stringID) > -1:
        print 'Found!'

Note that find returns the index where the substring you look for is
found, and it returns -1 if the substring is not found. The problem is
that -1 is a valid index to refer to a character in a string (actually
it refers to the last character of the string), so be careful with
interpreting the results of the find method.

francesco



More information about the Python-list mailing list