list previous or following list elements

norseman norseman at hughes.net
Fri Jun 27 02:12:51 CEST 2008


Terry Reedy wrote:
> 
> 
> 
> antar2 wrote:
>> Hello
>>
>>
>> Suppose I have a textfile (text1.txt) with following four words:
> 
> I see seven.  Just say 'list of words'
>>
>> Apple
>> balcony
>> cartridge
>> damned
>> paper
>> bold
>> typewriter
>>
>> and I want to have a python script that prints the words following the
>> word starting with the letter b (which would be cartridge) or
>> differently put, a script that prints the element following a
>> specified element:
>>
>> I am more experienced in Perl, and a beginner in python
>>
>> I wrote a script that - of course - does not work, that should print
>> the element in a list following the element that starts with a b
> 
> I believe
> wordlist = open('words.txt','r').read().split('\n')

using copy/paste: yes it does

> should give you the list in Python.  In any case,
> 
> wordlist = ['Apple','balcony', 'cartridge',
> 'damned', 'paper', 'bold', 'typewriter']
> for i, word in enumerate(wordlist):
>     if word[0] == 'b':
>         print(wordlist[i+1]) # 3.0
>         break
> 
> #prints cartridge (in 3.0)
> 

using copy/paste: same (correct) result in python 2.5.2
                   for wordlist = open...   AND for wordlist = [....

norseman



More information about the Python-list mailing list