Search code examples
pythonpercent-encoding

Turn a hex string into a percent encoded string in Python


I have a string. It looks like s = 'e6b693e6a0abe699ab'.

I want to put a percent sign in front of every pair of characters, so percentEncode(s) == '%e6%b6%93%e6%a0%ab%e6%99%ab'.

What's a good way of writing percentEncode(s)?

(Note, I don't care that unreserved characters aren't converted into ASCII.)

I can think of big verbose ways of doing this, but I want something nice and simple, and while I'm fairly new to Python, I'd be suprised if Python can't do this nicely.


Solution

  • >>> ''.join( "%"+i+s[n+1] for n,i in enumerate(s)  if n%2==0 )
    '%e6%b6%93%e6%a0%ab%e6%99%ab'
    

    Or using re

    >>> import re
    >>> re.sub("(..)","%\\1",s)
    '%e6%b6%93%e6%a0%ab%e6%99%ab'