def escape(to_escape, safe=SAFE, escape_char=ESCAPE_CHAR, allow_collisions=False):
if isinstance(to_escape, bytes):<EOL><INDENT>to_escape = to_escape.decode('<STR_LIT:utf8>')<EOL><DEDENT>if not isinstance(safe, set):<EOL><INDENT>safe = set(safe)<EOL><DEDENT>if allow_collisions:<EOL><INDENT>safe.add(escape_char)<EOL><DEDENT>elif escape_char in safe:<EOL><INDENT>safe.remove(escape_char)<EOL><DEDENT>chars = []<EOL>for c in to_escape:<EOL><INDENT>if c in safe:<EOL><INDENT>chars.append(c)<EOL><DEDENT>else:<EOL><INDENT>chars.append(_escape_char(c, escape_char))<EOL><DEDENT><DEDENT>return u'<STR_LIT>'.join(chars)<EOL>
Escape a string so that it only contains characters in a safe set.

    Characters outside the safe list will be escaped with _%x_,
    where %x is the hex value of the character.

    If `allow_collisions` is True, occurrences of `escape_char`
    in the input will not be escaped.

    In this case, `unescape` cannot be used to reverse the transform
    because occurrences of the escape char in the resulting string are ambiguous.
    Only use this mode when:

    1. collisions cannot occur or do not matter, and
    2. unescape will never be called.

    .. versionadded: 1.0
        allow_collisions argument.
        Prior to 1.0, behavior was the same as allow_collisions=False (default).