My problem is to convert a string in python into an array in the following way. I have to split the string into 8byte parts. I didn't find anything like this online. Basically, I want to create the following PHP code in python:
$eight_byte_packages_array=str_split($data, 8);
In PHP function str_split
will split into bytes, rather than characters when dealing with a multi-byte encoded string.
If you want to simulate this function in Python 3 first you have to convert strings to bytes.
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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.