Daniel Börg
Daniel Börg

Reputation: 21

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!

Upvotes: 0

Views: 281

Answers (2)

a_guest
a_guest

Reputation: 36339

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?

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799520

Too much work.

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

Upvotes: 2

Related Questions