【发布时间】:2020-05-18 10:46:40
【问题描述】:
text = "hello world what is happening"
encodedText = text.encode('utf-16') #Encoding the input text
textReplaced = encodedText.replace('h'.encode('utf-16'), 'Q'.encode('utf-16')) #Doing the replacement of an encoded character by another encoded character
print('Input : ', text)
print('Expected Output : Qello world wQat is Qappening')
print('Actual Output : ', textReplaced.decode('utf-16'))
print('Encoded h : ', 'h'.encode('utf-16'))
print('Encoded Q : ', 'Q'.encode('utf-16'))
print('Encoded Actual Output : ', textReplaced)
输出:
Input : hello world what is happening
Expected Output : Qello world wQat is Qappening
Actual Output : Qello world what is happening
Encoded h : b'\xff\xfeh\x00'
Encoded Q : b'\xff\xfeQ\x00'
Encoded Actual Output : b'\xff\xfeQ\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00 \x00w\x00h\x00a\x00t\x00 \x00i\x00s\x00 \x00h\x00a\x00p\x00p\x00e\x00n\x00i\x00n\x00g\x00'
代码的问题在于,由于编码字符对每个编码字符串或字符都有一个前缀 b',因此仅在编码输入中的第一次出现时进行替换。
【问题讨论】:
-
要求是对编码的输入文本进行替换,而不是直接在输入文本上进行替换
标签: python string character-encoding byte utf-16