Wrap color syntax around characters using indices and return it.

    fg and bg specify foreground- and background colors, respectively.

def formatbyindex(string, fg=None, bg=None, indices=[]):
    """Wrap color syntax around characters using indices and return it.

    fg and bg specify foreground- and background colors, respectively.

    """
    if not string or not indices or (fg is bg is None):
        return string

    result, p = '', 0

    # The lambda syntax is necessary to support both Python 2 and 3
    for k, g in itertools.groupby(enumerate(sorted(indices)),
                                  lambda x: x[0]-x[1]):
        tmp = list(map(operator.itemgetter(1), g))
        s, e = tmp[0], tmp[-1]+1

        if s < len(string):
            result += string[p:s]
            result += formatcolor(string[s:e], fg, bg)
            p = e

    if p < len(string):
        result += string[p:]

    return result