2013-04-22 130 views
1

我有麻烦了解编码是如何工作的:解码Python字符串

为什么Python代码字符串内进行编码:

s = 'Au\xc3\x9fenformat\n' 
print s.encode('utf-8') 
>>>Außenformnat 

但是,如果我从一个文本文件中读取这样的字符串,我得到:

f = open('out.txt', 'r') 
data = f.read() 
print data.encode('utf-8') 
>>>Au\xc3\x9fenformat\n 

有什么建议吗?

+1

你的意思*解码*?而你正在阅读*文本文件*,而不是从这里的sqlite数据库。 – 2013-04-22 14:52:33

+0

是解码(但在第一个例子中它给了我相同的结果!?)。我有文本文件和sqlite数据库的问题,数据库的例子更复杂,我认为这是由于同样的问题。我可以发布它,如果它不是... – snowflake 2013-04-22 15:09:11

+2

在你做之前,请确保你已经阅读[Python Unicode HOWTO](http://docs.python.org/2/howto/unicode.html),然后阅读[这篇文章](http://joelonsoftware.com/articles/Unicode.html)和[this too too](http://nedbatchelder.com/text/unipain.html)。 'sqlite3'模块处理Unicode很好,但是请验证[模块文档](http://docs.python.org/2/library/sqlite3.html)以确保您没有意外地错误配置内容。 – 2013-04-22 15:11:03

回答

3

试试这个,你应该看到文件的内容正确打印:

f = open('out.txt', 'r') 
data = f.read() 
print data.decode('string_escape') 

这是因为在该文件中的TXT反斜线被转义:

>>> open('out.txt').read() 
'Au\\xc3\\x9fenformat\\n\n' 
+0

啊,谢谢你的工作......我从来没有来过这个...... – snowflake 2013-04-23 06:50:02

+0

是的,它非常棘手;) – 2013-04-23 20:37:27

0
>>> f = open('out.txt', 'r') 
>>> data= f.read() 
>>> print data.decode("string_escape") 
ußenformat