Split a string to even sized chunks

后端 未结 8 2273
粉色の甜心
粉色の甜心 2020-11-27 23:05

How would I be able to take a string like \'aaaaaaaaaaaaaaaaaaaaaaa\' and split it into 4 length tuples like (aaaa,aaaa,aaaa

8条回答
  •  盖世英雄少女心
    2020-11-27 23:10

    I think this method is simpler. But the message length must be split with split_size. Or letters must be added to the message. Example: message = "lorem ipsum_" then the added letter can be deleted.

    message = "lorem ipsum"
    
    array = []
    
    temp = ""
    
    split_size = 3
    
    for i in range(1, len(message) + 1):
        temp += message[i - 1]
    
        if i % split_size == 0:
            array.append(temp)
            temp = ""
    
    print(array)
    

    Output: ['lor', 'em ', 'ips']

提交回复
热议问题