gpt4 book ai didi

python - Unicode 字符串 Python

转载 作者:太空宇宙 更新时间:2023-11-04 01:37:42 25 4
gpt4 key购买 nike

我需要将包含度数符号 (°) 的字符串写入文件。

这个字符串存储在变量中,正如预期的那样,当我尝试:f.write(myVariable.encode('utf-8')) 我得到 UnicodeDecodeError。

如果我尝试将此字符串写入如下文件:

x = u'aaa°°bbb'
f.write(encode(x))

工作正常,但我不能在我的代码中编写 x = u'aaa°°bbb' 因为 'aaa°°bbb' 来自数据库它存储在一个变量中,如果我尝试 newVar = unicode(myVariable),我会得到 UnicodeDecodeError

我需要将 myVariable 传递给“u”python 运算符...我该怎么做?

最佳答案

检索后使用数据库使用的任何编码对其进行解码。

s.decode('latin1')

当然,如果它首先在数据库中被错误编码,那么您将需要以某种方式进行补偿。

s.encode('latin1').decode('utf8')

关于python - Unicode 字符串 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8271854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com