0

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);
mx0
  • 6,445
  • 12
  • 49
  • 54
Kiftau
  • 43
  • 1
  • 5
  • 3
    Duplicate of http://stackoverflow.com/questions/9475241/split-python-string-every-nth-character – Błotosmętek Jun 07 '17 at 09:50
  • 2
    Possible duplicate of [Split python string every nth character?](https://stackoverflow.com/questions/9475241/split-python-string-every-nth-character) – Yu Jiaao Jun 07 '17 at 13:13

1 Answers1

0

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']
mx0
  • 6,445
  • 12
  • 49
  • 54