Is there a method that returns a character at a specified index?

Bengt Richter bokr at oz.net
Mon Oct 27 10:54:54 EST 2003


On Sun, 26 Oct 2003 21:11:34 -0500, "Michael Loomington" <mloomington at yahoo.ca> wrote:

>Couldn't find anything here
>http://www.python.org/doc/2.3.2/lib/string-methods.html
>
>I need to cycle through lines in a file that contain words and compare it to
>a string thats given, call it SSS to see if the words in the file can be
>written from SSS.  I am planning to grab each letter from the word one at a
>time and removing it from SSS and if the letter doesn't exist then I will go
>on to the next word.  That's why I need a method that returns a letter at
>each index.  Maybe there an easier way of doing this.
>
I'm not sure what you intend to do if you find that "words in the file can be
written from SSS," but perhaps you will need to know where in SSS the words are?
Perhaps you can get something useful from the snippet below, which suggests checking
for word availability in SSS by using a dict. Otherwise if SSS is big, you will be
re-scanning half of SSS each time on the average to find a word, and all of it if
the word is not there, so it will be inefficient. I split out the words in the lines
assuming spaces as delimiters, but you may need to use a regex to split away punctuation
marks as well, depending on your actual application. Obviously you could get lines from
a file with "for line in file('foo.txt'):" instead of the "for line in lines:" below,
but mind the '\n' and possible other leading and trailing white space that you get from
iterating through a file by lines.

 >>> SSS = 'nuts bolts screws nails'
 >>> SSS
 'nuts bolts screws nails'
 >>> sslist = SSS.split()
 >>> sslist
 ['nuts', 'bolts', 'screws', 'nails']
 >>> ssdict = dict([(w, (SSS.index(w), len(w))) for w in sslist])
 >>> ssdict
 {'screws': (11, 6), 'nails': (18, 5), 'nuts': (0, 4), 'bolts': (5, 5)}
 >>> lines = """\
 ... line 1 has nuts and bolts
 ... line 2 has screws and nails
 ... line 3 has no words from SSS
 ... """.splitlines()
 >>> lines
 ['line 1 has nuts and bolts', 'line 2 has screws and nails', 'line 3 has no words from SSS']
 >>> for line in lines:
 ...     print 'Line: %r' % line
 ...     words = line.split()
 ...     for word in words:
 ...         if word in ssdict:
 ...             print '    %r is %s chars starting at %s in SSS' %(
 ...                    word, ssdict[word][1], ssdict[word][0])
 ...
 Line: 'line 1 has nuts and bolts'
     'nuts' is 4 chars starting at 0 in SSS
     'bolts' is 5 chars starting at 5 in SSS
 Line: 'line 2 has screws and nails'
     'screws' is 6 chars starting at 11 in SSS
     'nails' is 5 chars starting at 18 in SSS
 Line: 'line 3 has no words from SSS'

Regards,
Bengt Richter




More information about the Python-list mailing list