简体   繁体   中英

How to decode hex values from a string in python

I am trying to decode the hex values inside my string so at the end I have one "readable" string.

For example:

encoded_string = 'videoplayback%253Fexpire%253D1532566750%2526mime%253Dvideo%25252Fmp4%2526key%253Dyt6%2526mt%253D1532544983%2526fvip%253D5%2526i'

Each hex value is indicated by a %-symbol and the length of the value can differentiate. What I tried is to decode the string manually:

encoded_string = encoded_string.replace('%253A', '\x25\x3A')
encoded_string = encoded_string.replace('%252F', '\x25\x2F')
encoded_string = encoded_string.replace('%253F', '\x25\x3F')
encoded_string = encoded_string.replace('%253D1532566750', '\x25\x3D\x15\x32\x56\x67\x50')

Now I need help with a function that is able to find the hex values and decode them.

Thank you guys!

Too much work.

>>> urllib.parse.unquote(urllib.parse.unquote(encoded_string))
'videoplayback?expire=1532566750&mime=video%2Fmp4&key=yt6&mt=1532544983&fvip=5&i'

You can use regular expressions for that:

re.sub(
    r'%([A-F0-9]{4,14})',
    lambda m: str(int(m.groups()[0], 16)),
    encoded_string
)

Though I'm not sure if you just want to do URL decoding?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM