【发布时间】:2020-01-03 01:04:08
【问题描述】:
我想创建一个包含我的字符串的 8 字节大小的变量。
byte = 8_bytes_variable
str = 'hello'
# Put str inside byte while byte still remains of size 8 bytes.
【问题讨论】:
标签: string python-2.7 byte
我想创建一个包含我的字符串的 8 字节大小的变量。
byte = 8_bytes_variable
str = 'hello'
# Put str inside byte while byte still remains of size 8 bytes.
【问题讨论】:
标签: string python-2.7 byte
您可以先在字符串的开头添加一些空格来格式化字符串。在这里,我假设每个字符占用 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()
【讨论】: