【问题标题】:remove prefix b in encoded text in python删除python编码文本中的前缀b
【发布时间】: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


【解决方案1】:

问题在于替换字节包括字节顺序标记(b'\xff\xfe'),它只出现在字节串的开头。如果您必须在 bytes 而不是 str 中进行替换,则需要使用与系统字节序匹配的 UTF-16 编码(或字节,这可能不一样)。

假设字节的字节序是您系统的字节序,这将起作用:

>>> import sys
>>> enc = 'utf-16-le' if sys.byteorder == 'little' else 'utf-16-be'
>>> textReplaced = encodedText.replace('h'.encode(enc), 'Q'.encode(enc))
>>> textReplaced.decode('utf-16')
'Qello world wQat is Qappening'

更简单、更灵活的方法是使用bytes.translate 方法。

>>> trans_table = bytes.maketrans('h'.encode('utf-16'), 'Q'.encode('utf-16'))
>>> print(encodedText.translate(trans_table).decode('utf-16'))
Qello world wQat is Qappening

【讨论】:

    猜你喜欢
    • 2017-03-13
    • 1970-01-01
    • 2020-08-20
    • 2013-03-20
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    相关资源
    最近更新 更多