def rtf_encode(text):
    """
    Convert unicode text to rtf format with substitution of non-ascii
    characters. (Based on Martijn Pieters' code.)
    """
    return ''.join(['\\u%i?' % (ord(e) if e < u'\u8000' else ord(e) - 65536) if (e > '\x7f' or e < '\x20' or e in u'\\{}') else str(e) for e in text])