解码字符串中的字符串
我正在使用 urllib2
,想从一个 Response
对象中提取出可打印的头信息。
目前我用 str(response.info())
来打印,但打印出来的其实是一个 Python 字符串(至少我理解是这样的)。
(Pdb) p str(response.info())
'Date: Tue, 23 Feb 2010 03:12:26 GMT\r\nServer: Apache\r\nVary: Accept-Encoding,User-Agent\r\nContent-Encoding: gzip\r\nContent-Length: 9045\r\nConnection: close\r\nContent-Type: text/html; charset=ISO-8859-1\r\n'
我需要把这个字符串变成一个“真正的”字符串,比如通过某种方式来评估它。理论上我找到的最佳解决方案是使用:
s = str(response.info())
print s.decode("string_escape")
但是这个方法不管用。更让人困惑的是,字符串中的引号该怎么处理,调用 eval(s)
和 str(s)
也都不行。
有没有更好的方法来提取响应中的原始头信息,而不需要引号,或者有办法像上面那样解码字符串 s
?
3 个回答
0
response.info()
返回的是一个 httplib.HTTPMessage
对象,它的表现方式像一个字典,也就是可以用键值对的方式来获取信息。
info = response.info()
for k, v in info.items():
print '%s: %s' % (k, v)
简单来说,你的做法是不对的。
0
从pdb来看,这个应该可以用:
print str(response.info())
不过我不确定这是否能解答你的问题。
2
str(info())
确实会给出一个正常的字符串:
>>> import urllib2
>>> f = urllib2.urlopen('http://tejp.de')
>>> print str(f.info())
Connection: close
Vary: Accept-Encoding
Content-Type: text/html
Accept-Ranges: bytes
ETag: "-807357257"
Last-Modified: Wed, 01 Jul 2009 10:05:34 GMT
Content-Length: 285
Date: Tue, 23 Feb 2010 03:24:10 GMT
Server: lighttpd/1.4.19
只有调试器的 p
命令会以转义的形式打印这个字符串。