我想在python中连接一些字符串(波斯语字符串):
for t in lstres:
with conn:
c = conn.cursor()
q="SELECT fa FROM words WHERE en ='"+t+"'"
c.execute(q)
lst=c.fetchall()
if lst:
W.append(lst)
else:
W.append(t)
cnum=1
for can in W:
cnum=cnum*len(W)
candida=Set()
for ii in range(1,min(20,cnum)):
candid=""
for w in W:
candid+=str(" "+random.choice (w)[0]).encode('utf-8')
candida.add(candid)
但它说:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd8 in position 1: ordinal not in range(128)
问题是什么?
最佳答案
Python 正在尝试进行从 unicode 字符串到 ASCII 编码字符串的隐式类型转换。从您发布的内容中很难判断发生这种情况的位置,但最好确保您始终使用 unicode。为此,您需要在所有字符串前面添加一个 u
,如下所示:u"A unicode string"
并始终使用 unicode()
而不是 str()
。
Unicode 经常被英语程序员和教程所忽视,因为在英语中你可以只使用 ASCII 编码的字符。不幸的是,世界其他地方都因此受到影响,因为大多数语言使用 ASCII 不支持的字符。查看 Python Unicode HOWTO 可能会有用。获得有关 Unicode 良好编程实践的一些指导。
我还发现了this文章非常有用。
关于python - 编码Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12410284/