def replaceStringByIndex(s, newstring, index, nofail=False):
    # raise an error if index is outside of the string
    if not nofail and index not in xrange(len(s)):
        raise ValueError("index outside given string")

    # if not erroring, but the index is still not in the correct range..
    if index < 0:  # add it to the beginning
        return newstring + s
    if index > len(s):  # add it to the end
        return s + newstring

    # insert the new string between "slices" of the original
    return s[:index] + newstring + s[index + 1:]