def ascii(str):
    """Return a string with all non-ascii characters hex-encoded"""
    if type(str) != type(''):
        return map(ascii, str)
    rv = ''
    for c in str:
        if c in ('\t', '\n', '\r') or ' ' <= c < chr(0x7f):
            rv = rv + c
        else:
            rv = rv + '\\' + 'x%02.2x' % ord(c)
    return rv