Create a list (of tuples?) from two lists of different sizes
Question: I am stuck trying to perform this task and while trying I can't help thinking
there will be a nicer way to code it than the way I have been trying.

I have a line of text and a keyword. I want to make a new list going down each
character in each list. The keyword will just repeat itself until the end of
the list. If there are any non-alpha characters the keyword letter will not be
used.

For example:

    
    
    Keyword="lemon"
    Text="hi there!"
    

would result in

    
    
    ('lh', 'ei', ' ', 'mt' , 'oh', 'ne', 'lr', 'ee', '!')
    

Is there a way of telling python to keep repeating over a string in a loop, ie
keep repeating over the letters of lemon?

I am new to coding so sorry if this isn't explained well or seems strange!


Answer: You've got two questions mashed into one. The first is: how do you remove non-
alphanumeric chars from a string? You can do it a few ways, but regular
expression substitution is a nice way.

    
    
    import re
    
    def removeWhitespace( s ):
        return re.sub( '\s', '', s )
    

The second part of the question is about how to keep looping through the
keyword, until the text line is consumed. You can write this as:

    
    
    def characterZip( keyword, textline ):
        res = []
        textline = removeWhitespace(textline)
        textlen = len(textline)
        for i in xrange(textlen)):
            res.append( '%s%s' % (keyword[i%len(keyword)], textline[i]) )
        return res
    

Most pythonistas will look at this and see opportunity for refactoring. The
patten that this code is trying to achieve is in functional programming termed
a `zip`. The quirk is that in this case you're doing something slightly non-
normative with the repeating characters of the keyword, this too has an
equivalent, the
[cycle](http://docs.python.org/library/itertools.html#itertools.cycle)
function in the itertools module.

    
    
    from itertools import cycle, islice, izip
    
    def characterZip( keyword, textline ):
        textline = removeWhitespace(textline)
        textlen = len(textline)
        it = islice( izip(cycle(keyword), textline), textlen )
        return [ '%s%s' % val for val in it ]
    

