【问题标题】:Convert url encoded string into python unicode string将 url 编码字符串转换为 python unicode 字符串
【发布时间】:2011-09-22 17:42:38
【问题描述】:

我有以以下形式编码的字符串:La+Cit%C3%A9+De+la+West,我存储在 python 的 SQLite VARCHAR 字段中。

这些显然是 UTF-8 编码的二进制字符串转换为 urlencoded 字符串。 问题是如何将其转换回 unicode 字符串。 s = 'La+Cit%C3%A9+De+la+West'

我使用了 urllib.unquote_plus(s) python 函数,但它不会将 %C3%A9 转换为 unicode char。我看到的是“La Cité De la West”,而不是预期的“La Cité De la West”。

我在 Ubuntu 上运行我的代码,而不是 Windows,编码是 UTF-8。

【问题讨论】:

    标签: python unicode


    【解决方案1】:

    正如我们所讨论的,问题似乎在于您从 unicode 对象开始,而不是字符串。你想要一个字符串:

    >>> import urllib
    >>> s1 = u'La+Cit%C3%A9+De+la+West'
    >>> type(s1)
    <type 'unicode'>
    >>> print urllib.unquote_plus(s1)
    La Cité De la West
    
    >>> s2 = str(s1)
    >>> type(s2)
    <type 'str'>
    >>> print urllib.unquote_plus(s2)
    La Cité De la West
    
    >>> import sys
    >>> sys.stdout.encoding
    'UTF-8'
    

    【讨论】:

    • 你的例子对我来说也是一样的。字符串是从 SQLite 数据库中的 VARCHAR 字段中提取的事实吗?
    • type(s) 使用您的示例返回 str 。当 s = u"La+Cit%C3%A9+De+la+West" 时,type(s) 返回 unicode,print unquote_plus(s) 返回 'La Cité De la West'。因此问题是 s 的初始类型。使用 print unquote_plus(str(s)) 解决了我的问题。 !!
    • 好多了。我做了一些编辑以使其更清晰,并为没有经验的程序员添加了 import 语句。
    • 问题是因为 SQLite 将 CHAR 数组作为 unicode 字符串而不是 str 字符串返回。在调用 unquote_plus() 之前使用 str() 解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    相关资源
    最近更新 更多