[英]python 3, unicode conversion, two \u0000 as one character
我的python3腳本通過管道從c ++程序接收字符串。 通過Unicode代碼點編碼的字符串。 我需要正確解碼它。
例如,考慮包含西里爾符號的字符串: 'тест test'
嘗試使用python3: print('тест test'.encode())
對此字符串進行編碼。 我們得到了b'\\xd1\\x82\\xd0\\xb5\\xd1\\x81\\xd1\\x82 test'
C ++程序對此字符串進行編碼,如: b'\Ñ\\Ð\µ\Ñ\\Ñ\ test'
編碼字符串看起來非常相似 - python3使用
\\x
(2bits)而c ++程序使用\\u\u003c/code> (4bits)。
但我無法弄清楚如何將
b'\Ñ\\Ð\µ\Ñ\\Ñ\ test'
為'тест test'
b'\Ñ\\Ð\µ\Ñ\\Ñ\ test'
進行'тест test'
。 'тест test'
主要問題 - python3將b'\Ñ\\Ð\µ\Ñ\\Ñ\'
作為8個字符的字符串,但它只包含4個字符
如果您從C ++收到的字符串在Python中如下:
s = b'\u00D1\u0082\u00D0\u00B5\u00D1\u0081\u00D1\u0082 test'
然后這將解碼它:
result = s.decode('unicode-escape').encode('latin1').decode('utf8')
print(result)
輸出:
тест test
第一階段將接收的字節字符串轉換為Unicode字符串:
>>> s1 = s.decode('unicode-escape')
>>> s1
'Ñ\x82еÑ\x81Ñ\x82 test'
不幸的是,Unicode代碼點實際上是UTF-8字節值。 latin1
編碼是前256個Unicode碼點的1:1映射,因此使用此編解碼器進行編碼會將代碼點轉換回字節字符串中的字節值:
>>> s2 = s1.encode('latin1')
>>> s2
b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82 test'
現在可以將字節字符串解碼為正確的Unicode字符串:
>>> s3 = s2.decode('utf8')
>>> s3
'тест test'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.