在 python 中模拟 JS decodeURIComponent 和 unescape

Elo*_*ati 5 javascript python-2.7

我想模仿我们在 Python 中的 JS 中的 decodeURIComponent 和 unescape。

例如我得到这个字符串:

%25D7%2590%25D7%2591%25D7%2592
Run Code Online (Sandbox Code Playgroud)

在 JS 中,我可以这样做:

decodeURIComponent(unescape('%25D7%2590%25D7%2591%25D7%2592'))
Run Code Online (Sandbox Code Playgroud)

并得到:???

我在 Python 中找不到任何方法,如果相关,我正在使用 Tornado Web...

xyr*_*res 9

urllib.parse.unquote在Python(或urlparse.unquote在Python 2)做到这一点。

但我不明白为什么你发布的字符串被 urlencoded两次。因为单个 urlencoded 字符串可以仅使用decodeURIComponent(不带unescape)来解码。

无论如何,此 Python 版本将是:

from urllib.parse import unquote # For Python 2 use: from urlparse import unquote

# decode twice because the string has been encoded twice.
unquote(unquote('%25D7%2590%25D7%2591%25D7%2592'))
Run Code Online (Sandbox Code Playgroud)

对于单个 urlencoded 字符串,您只需使用unquote一次。