Python: 使用字符串格式化左对齐并填充 bytes 对象
可以使用字符串格式化中的格式化字符串来实现将 bytes 对象左对齐并填充 \0 的操作,具体代码如下:
bytes_obj = b'hello'
left_aligned = '{:<10}'.format(bytes_obj.decode('utf-8'))
left_aligned_bytes = left_aligned.encode('utf-8')
解释:
- 首先定义一个 bytes 对象
bytes_obj,值为 b'hello'。 - 将
bytes_obj解码为字符串,使用字符串格式化中的<符号进行左对齐,并指定总宽度为 10,得到左对齐后的字符串left_aligned。 - 将
left_aligned编码为 bytes 对象,得到左对齐后的 bytes 对象left_aligned_bytes。其中编码方式使用 utf-8,可以根据实际情况进行修改。
执行上述代码后,left_aligned_bytes 的值为 b'hello ',左对齐并填充了 5 个空格和一个 \0。
原文地址: https://www.cveoy.top/t/topic/mhyF 著作权归作者所有。请勿转载和采集!