Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 从python 3中字节的字符串表示形式中检索字节_Python 3.x_Utf 8 - Fatal编程技术网

Python 3.x 从python 3中字节的字符串表示形式中检索字节

Python 3.x 从python 3中字节的字符串表示形式中检索字节,python-3.x,utf-8,Python 3.x,Utf 8,以下代码段在输出正确的UTF8字符表示法时非常有效: a = b"Tenemos la Soluci\xc3\xb3n" a.decode('utf8') 'Tenemos la Solución' # correct output 但在我的用例中,实际字节作为字符串存储在数据库中。在这种情况下,如何使用正确的UTF8表示检索输出 a = "Tenemos la Soluci\xc3\xb3n" # retrieved from Database b = bytes(a, 'utf8') b.

以下代码段在输出正确的UTF8字符表示法时非常有效:

a = b"Tenemos la Soluci\xc3\xb3n"
a.decode('utf8')
'Tenemos la Solución' # correct output
但在我的用例中,实际字节作为字符串存储在数据库中。在这种情况下,如何使用正确的UTF8表示检索输出

a = "Tenemos la Soluci\xc3\xb3n" # retrieved from Database
b = bytes(a, 'utf8')
b.decode('utf8')
'Tenemos la Solución' # incorrect output
请建议如何解决此问题。

您所拥有的是,例如,当UTF-8编码文本存储在配置为ISO-8859-1或类似编码的数据库中时,就会发生这种情况
latin1
是Unicode代码点到等效字节的1:1映射,假设Unicode字符串仅包含U+0000到U+00FF,并可用于解决此问题:

>>> a = "Tenemos la Soluci\xc3\xb3n" # retrieved from Database
>>> a.encode('latin1').decode('utf8')
'Tenemos la Solución'