def next_generation(state,rules):
    """ Return the string that results from applying RULES to STATE. """
    next_state = ''
    for i in range(2,len(state) - 2):
        pattern = state[i - 2:i + 3]
        if pattern in rules:
            next_state += rules[pattern]
        else:
            next_state += '.'

    return '..' + next_state + '..'