【发布时间】:2018-10-01 17:12:27
【问题描述】:
我需要转换一个字符串,以便将其转换为人类可读的格式。
s = "that’s awful, Find – Best Quotes, “Music gives a soul to the universe, wings to the mind, flight to the imagination and life to everything.” ― Plato."
我想将此字符串转换为"that’s awful, Find - Best Quotes, "Music gives a soul to the universe, wings to the mind, flight to the imagination and life to everything." ― Plato."
但我面临多个问题 w.r.t.不同的场景。
-
当我使用
print(str(s.encode('cp1252',"ignore"),'utf-8'))我明白了UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 4 中的字节 0x92
-
当我使用
print(str(s.encode('cp1252'),'utf-8',"ignore"))我明白了UnicodeEncodeError: 'charmap' 编解码器无法对位置 151 中的字符 '\u2015' 进行编码
-
当我使用
print(str(s.encode('cp1252',"ignore"),'utf-8',"ignore"))然后可以预见,在省略所有撇号、单引号和双引号后,我得到的字符串没有错误“那太可怕了,查找 – 最佳语录,音乐赋予宇宙灵魂,赋予思想翅膀,飞向想象,赋予一切生命。柏拉图。”
【问题讨论】:
-
所以第三种情况是有效的。似乎忽略转换中的错误有助于不引发错误并且字符串转换。还有一个错字是案例3,它是
s.encode而不是string.encode -
但我不想松开撇号、单引号和双引号。所以基本上忽略错误是行不通的。
标签: python python-3.x encoding utf-8