Split a string to even sized chunks

后端 未结 8 2154
粉色の甜心
粉色の甜心 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:07

    Another solution using regex:

    >>> s = 'aaaaaaaaaaaaaaaaaaaaaaa'
    >>> import re
    >>> re.findall('[a-z]{4}', s)
    ['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa']
    >>>
    
    0 讨论(0)
  • 2020-11-27 23:10

    Use textwrap.wrap:

    >>> import textwrap
    >>> s = 'aaaaaaaaaaaaaaaaaaaaaaa'
    >>> textwrap.wrap(s, 4)
    ['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaa']
    
    0 讨论(0)
  • 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']

    0 讨论(0)
  • 2020-11-27 23:19
    s = 'abcdef'
    

    We need to split in parts of 2

    [s[pos:pos+2] for pos,i in enumerate(list(s)) if pos%2 == 0]
    

    Answer:

    ['ab', 'cd', 'ef']
    
    0 讨论(0)
  • 2020-11-27 23:19
    s = 'abcdefghi'
    

    k - no of parts of string

    k = 3
    

    parts - list to store parts of string

    parts = [s[i:i+k] for i in range(0, len(s), k)]
    

    parts --> ['abc', 'def', 'ghi']

    0 讨论(0)
  • 2020-11-27 23:25

    You could use the grouper recipe, zip(*[iter(s)]*4):

    In [113]: s = 'aaaaaaaaaaaaaaaaaaaaaaa'
    
    In [114]: [''.join(item) for item in zip(*[iter(s)]*4)]
    Out[114]: ['aaaa', 'aaaa', 'aaaa', 'aaaa', 'aaaa']
    

    Note that textwrap.wrap may not split s into strings of length 4 if the string contains spaces:

    In [43]: textwrap.wrap('I am a hat', 4)
    Out[43]: ['I am', 'a', 'hat']
    

    The grouper recipe is faster than using textwrap:

    In [115]: import textwrap
    
    In [116]: %timeit [''.join(item) for item in zip(*[iter(s)]*4)]
    100000 loops, best of 3: 2.41 µs per loop
    
    In [117]: %timeit textwrap.wrap(s, 4)
    10000 loops, best of 3: 32.5 µs per loop
    

    And the grouper recipe can work with any iterator, while textwrap only works with strings.

    0 讨论(0)
提交回复
热议问题