list previous or following list elements

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Thu Jun 26 20:44:44 EDT 2008


Terry Reedy:
> I believe
> wordlist = open('words.txt','r').read().split('\n')
> should give you the list in Python.

This looks better (but it keeps the newlines too. Untested. Python
2.x):

words = open("words.txt").readlines()
for i, word in enumerate(words):
    if word.startswith("b"):
        print words[i+1]
        break

Another possibility (untested, lazy, uses less memory, probably
better):

fin = open("words.txt")
last_word = fin.next()
for word in fin:
    if last_word.startswith("b"):
        print word
        break
    else:
        last_word = word
fin.close()

A note for the original poster: I suggest you to try to learn string
methods (not the string module), they are designed to avoid you to use
regular expressions most of the times, and they are faster and more
readable too. I have seen that people that learn Python coming from
Perl are often 'blind' to their existence.

Bye,
bearophile



More information about the Python-list mailing list