def nt_escape(node_string):
    """Properly escape strings for n-triples and n-quads serialization."""
    output_string = ''
    for char in node_string:
        if char == u'\t':
            output_string += '\\t'
        elif char == u'\n':
            output_string += '\\n'
        elif char == u'\r':
            output_string += '\\r'
        elif char == u'"':
            output_string += '\\"'
        elif char == u'\\':
            output_string += '\\\\'
        elif char >= u' ' and char <= u'!' or char >= u'#' and char <= u'[' or char >= u']' and char <= u'~':
            output_string += char
        elif char >= u'\x7f' and char <= u'\uffff':
            output_string += '\\u%04X' % ord(char)
        elif char >= u'𐀀' and char <= u'\U0010ffff':
            output_string += '\\U%08X' % ord(char)
    return output_string
