【问题标题】:Python String into 8 byte ArrayPython 字符串转换为 8 字节数组
【发布时间】:2017-06-07 09:47:14
【问题描述】:

我的问题是通过以下方式将python中的字符串转换为数组。我必须将字符串分成 8 字节的部分。我在网上没有找到类似的东西。基本上,我想在 python 中创建以下 PHP 代码:

$eight_byte_packages_array=str_split($data, 8);

【问题讨论】:

标签: php python arrays string bitwise-operators


【解决方案1】:

在PHP函数str_split

在处理多字节编码的字符串时将拆分为字节,而不是字符。

如果你想先在 Python 3 中模拟这个函数,你必须将字符串转换为字节。

def str_split(string, length):
    byte_string = string.encode('utf-8')
    return [byte_string[i:i+length] for i in range(0, len(byte_string), length)]

str_split("This is a test.", 8)
>>> [b'This is ', b'a test.']

str_split("これはテストです。", 8)
>>> [b'\xe3\x81\x93\xe3\x82\x8c\xe3\x81',
     b'\xaf\xe3\x83\x86\xe3\x82\xb9\xe3',
     b'\x83\x88\xe3\x81\xa7\xe3\x81\x99',
     b'\xe3\x80\x82']

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2014-03-07
  • 1970-01-01
  • 1970-01-01
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多