string - 如何将字符串转换为固定数量的字节?
问题描述
我想创建一个包含我的字符串的 8 字节大小的变量。
byte = 8_bytes_variable
str = 'hello'
# Put str inside byte while byte still remains of size 8 bytes.
解决方案
您可以首先通过在字符串开头添加一些空格来格式化字符串。在这里,我假设每个字符占用 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()
推荐阅读
- python - Python - 向时间序列数据集添加行
- java - GetterAndSetter 返回空的 ArrayList
- ios - 关于重用 UITouch 和 UIEvent 对象
- rx-java - 如果 RxJava 失败,如何恢复映射列表
- regex - 具有前瞻模式的 grep 命令不选择任何内容
- html - 文本换行时元素占用 100% 的宽度(flexbox)
- xml - 旧版本产品如何提供方案?
- ruby-on-rails - 如何获得关键字搜索 ransack rails 的最接近匹配
- outlook-addin - 我可以为要使用发送按钮创建的会议设置扩展属性吗?
- regex - 如何从正则表达式模式中只拒绝一个字符串