【发布时间】:2011-09-23 14:26:56
【问题描述】:
如何像这样解码 unicode 字符串:
what%2527s%2bthe%2btime%252c%2bnow%253f
像这样进入ascii:
现在是什么+时间+现在
【问题讨论】:
-
你开头的字符串不是 unicode 格式。
-
"ascii" vs "unicode" 与您遇到的问题完全不同。真的,简直不能再不同了。
如何像这样解码 unicode 字符串:
what%2527s%2bthe%2btime%252c%2bnow%253f
像这样进入ascii:
现在是什么+时间+现在
【问题讨论】:
在您的情况下,字符串被解码了两次,因此我们需要取消引用两次才能将其取回
In [1]: import urllib
In [2]: urllib.unquote(urllib.unquote("what%2527s%2bthe%2btime%252c%2bnow%253f") )
Out[3]: "what's+the+time,+now?"
【讨论】:
unquote 可能想改成unquote_plus;我猜那些 +s 最初是空格,作为 HTML 表单提交(它对 + 的处理与常规 URL 编码略有不同)。但是,是的,双重编码的字符串是一个危险信号,表示“有人在这里做错了……”
这样的?
title = u"what%2527s%2bthe%2btime%252c%2bnow%253f"
print title.encode('ascii','ignore')
另外,看看this
【讨论】:
您可以使用以下方式转换 %(hex) 转义字符:
import re
def my_decode(s):
re.sub('%([0-9a-fA-F]{2,4})', lambda x: unichr(int(x.group(1), 16)), s)
s = u'what%2527s%2bthe%2btime%252c%2bnow%253f'
print my_decode(s)
生成 unicode 字符串
u'what\u2527s+the+time\u252c+now\u253f'
不确定如何将 \u2527 转换为单引号,或者在转换为 ascii 时删除 \u253f 和 \u252c 字符
【讨论】: