我试图编写一个Python函数,将UTF-8字符串的RLE编码为字节。给定"abbcccddddaaaaaa"
,它将返回b'\x01a\x02b\x03c\x04d\x06a'
我几乎解决了这个问题,只是我一直在用所需的格式将游程长度(整数)转换为十六进制,它类似于字符(^{
我需要一个函数,它将接受一个十进制数,并以'\x<hex form>'
的形式返回十六进制数。例如,这是chr()
对于最多31个数字的行为:
chr(1)
> '\x01'
chr(31)
> '\x1f'
但是,在31以上,它会打印字符
不起作用的事情:
hex(32)
> '0x20'
re.sub('0', '\', hex(32), count=1)
> SyntaxError: EOL while scanning string literal
re.sub('0', '\\', hex(32), count=1)
> error: bad escape (end of pattern) at position 0
re.sub('0', r'\\', hex(32), count=1)
> '\\x20'
预期结果:
my_func(32)
> '\x20'
使用格式字符串:
如果要覆盖字节字符串的显示,可以使用:
或者只使用一个函数:
相关问题 更多 >
编程相关推荐