0

I am retrieving a querystring from an API but I need it in another format for a different API. How can I use python3 to convert querystring1 so it'll be in the format given in querystring2? What character format is querystring1 and querystring2 in? They both should decode to 'q=score:>=100'.

querystring1 = 'q=score%3A%26amp%3Bgt%3B%3D100'

querystring2 = 'q=score%3A%3E%3D100'
bayman
  • 1,579
  • 5
  • 23
  • 46

1 Answers1

4

The second of these is a simple encoded querystring, which can be parsed with urllib.parse.unquote:

from urllib import parse
parse.unquote('q=score%3A%3E%3D100')

The first is trickier, because it's a querystring that (wrongly) contains double-encoded HTML entities. You need to use html.unescape to translate them:

import html
html.unescape(parse.unquote('q=score%3A%26amp%3Bgt%3B%3D100'))

To convert version 1 to version 2, you can parse and then re-encode. Note, you need to pass it through html.escape twice; the first will translate > to >, the second will translate that to >. (To be honest, you should really look into fixing whatever API is expecting that format, it's totally broken.)

data = parse.unquote('q=score%3A%3E%3D100')
parse.quote(html.escape(data))
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895