【问题标题】:mimic JS decodeURIComponent and unescape in python在 python 中模仿 JS decodeURIComponent 和 unescape
【发布时间】:2017-12-11 08:50:35
【问题描述】:

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

例如我得到这个字符串:

%25D7%2590%25D7%2591%25D7%2592

在 JS 中我可以这样做:

decodeURIComponent(unescape('%25D7%2590%25D7%2591%25D7%2592'))

并得到: 吖

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

【问题讨论】:

    标签: javascript python-2.7


    【解决方案1】:

    Python 中有 urllib.parse.unquote(或 Python 2 中的 urlparse.unquote)可以做到这一点。

    但我不明白为什么您发布的字符串是 urlencoded 两次。因为只需使用decodeURIComponent(不带unescape)就可以解码单个urlencoded 字符串。

    无论如何,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'))
    

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

    【讨论】:

    • 我知道这是一个旧线程,但遇到了同样的问题。 POST 请求中的数据将空格更改为“+”而不是“%20”,所以我使用 encodeURIComponent 将其强制为“%20”,但是在 POST 中,“%”被替换为“%25”。所以最后它看起来像“%2520”......这就是它被双引号的原因......
    • @kfinto 您可以在字符串上使用.replace(/\+/g, " ") 作为 CPU 升解决方案。代码看起来也不会那么混乱
    猜你喜欢
    • 1970-01-01
    • 2010-10-11
    • 2012-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多