当我尝试在Windows控制台中打印Unicode字符串时,出现UnicodeEncodeError: 'charmap' codec can't encode character ....错误.我认为这是因为Windows控制台不接受仅Unicode字符.最好的方法是什么??在这种情况下,有什么方法可以让Python自动打印而不是失败?
编辑: 我正在使用Python 2.5.
注意: @ LasseV.Karlsen回答带有复选标记有点过时(从2008年开始).请谨慎使用下面的解决方案/答案/建议!!
截至今天(2016年1月6日),@ JFSebastian答案更为相关.
我已经编写了我的程序来从文本文件中读取单词并将它们输入到 sqlite 数据库中,并将其视为字符串。但我需要输入一些包含日耳曼语 umlates 的单词:äöüß。
这是一段准备好的代码:
我用 # - - 编码:iso-8859-15 - - 和 # - - 编码:utf-8 - - 没有区别(!)
# -*- coding: iso-8859-15 -*-
import sqlite3
dbname = 'sampledb.db'
filename ='text.txt'
con = sqlite3.connect(dbname)
cur = con.cursor()
cur.execute('''create table IF NOT EXISTS table1 (id INTEGER PRIMARY KEY,name)''')
#f=open(filename)
#text = f.readlines()
#f.close()
text = u'süß'
print (text)
cur.execute("insert into table1 (id,name) VALUES (NULL,?)",(text,))
con.commit()
sentence = "The name is: %s" %(text,)
print (sentence)
f.close()
con.close()
Run Code Online (Sandbox Code Playgroud)
上面的代码运行良好。但我需要从包含“süß”一词的文件中读取“文本”。因此,当我取消注释 3 行( …