首页 > 解决方案 > 如何将字符串转换为固定数量的字节?

问题描述

我想创建一个包含我的字符串的 8 字节大小的变量。

byte = 8_bytes_variable
str = 'hello'
# Put str inside byte while byte still remains of size 8 bytes.

标签: stringpython-2.7byte

解决方案


您可以首先通过在字符串开头添加一些空格来格式化字符串。在这里,我假设每个字符占用 1 位。(汉字占多)

str = 'hello'
if len(str.encode('utf-8')) > 8:
    print("This is not possible!")
else:
    str2 = '{0: >8}'.format(str)    # adds needed space to the beginnig of str
    byte = str2.encode('utf-8')

为了稍后获取原始字符串,您可以使用lstrip()

str2 = byte.decode()
str = str2.lstrip()

推荐阅读