【问题标题】:How to convert string into fixed number of bytes?如何将字符串转换为固定数量的字节?
【发布时间】: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


    【解决方案1】:

    您可以先在字符串的开头添加一些空格来格式化字符串。在这里,我假设每个字符占用 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()
    

    【讨论】:

      猜你喜欢
      • 2020-06-28
      • 2014-10-09
      • 1970-01-01
      • 2023-02-26
      • 1970-01-01
      • 1970-01-01
      • 2011-12-23
      • 2010-10-17
      • 2013-10-05
      相关资源
      最近更新 更多