How to do the bytes equivalent of string.translate?

Viewed 191

Python provides the .translate() method on strings. It accepts a mapping from Unicode codepoints to strings, and uses it to replace any matching codepoint. I'm using this to escape special characters in HTML (<>&" to &lt; etc.) and URLs (many characters get percent-encoded).

For some reason, the .translate() function on bytes objects is much weaker: it accepts a bytes object of length 256, and uses it as a translation table. I need to do the same HTML and URL escaping on bytes objects, but this weaker .translate() function can't do it.

Is there another way to do this sort of multiple simultaneous search and replace on bytes objects? Doing .replace() multiple times seems super inefficient, especially for URL escaping where there are many bytes that need to be escaped.

0 Answers
Related