Searching and writing
Question: I need to write a program which looks for words with the same three middle
characters(each word is 5 characters long) in a list, then writes them into a
file like this :

    
    
    wasdy
    casde
    tasdf
    
    gsadk
    csade
    hsadi
    

Between the similar words i need to leave an empty line. I am kinda stuck. Is
there a way to do this? I use Python 3.2 .

Thanks for your help.


Answer: I would use the
[`itertools.groupby`](http://docs.python.org/library/itertools.html#itertools.groupby)
function for this. Assuming `wordlist` is a list of the words you want to
group, this code does the trick.

    
    
    import itertools
    
    for k, v in itertools.groupby(wordlist, lambda word: word[1:4]):
        # here, k is the key the words are grouped by, i.e. word[1:4]
        # and v is a list/iterable of the words in the group
        for word in v:
            print word
        print
    

`itertools.groupby(wordlist, lambda word: word[1:4])` basically takes all the
words, and groups them by `word[1:4]`, i.e. the three middle characters.
Here's the output of the above code with your sample data:

    
    
    wasdy
    casde
    tasdf
    
    gsadk
    csade
    hsadi
     
    

