【发布时间】:2017-06-07 09:47:14
【问题描述】:
我的问题是通过以下方式将python中的字符串转换为数组。我必须将字符串分成 8 字节的部分。我在网上没有找到类似的东西。基本上,我想在 python 中创建以下 PHP 代码:
$eight_byte_packages_array=str_split($data, 8);
【问题讨论】:
标签: php python arrays string bitwise-operators
我的问题是通过以下方式将python中的字符串转换为数组。我必须将字符串分成 8 字节的部分。我在网上没有找到类似的东西。基本上,我想在 python 中创建以下 PHP 代码:
$eight_byte_packages_array=str_split($data, 8);
【问题讨论】:
标签: php python arrays string bitwise-operators
在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']
【讨论】: