def esc_string(mystring, delim, esc_char='\\'):
    return (esc_char + delim).join([(s[:-1] if s.endswith(esc_char) else s) for
        s in mystring.split(delim)])
How to inject escape sequences in python