def context_before(string, index, contextnum):
    """gets the specified number of characters before the given index,
    or until the beginning of the string.
    """
    if contextnum < 0:
        raise ValueError("Context amount cannot be negative")

    bound = index - contextnum
    # start at beginning of string if contextnum is greater than length before
    if bound < 0:
        bound = 0

    return string[bound:index]