'How to split a string in to list where the number of string in the list is defined?

So if I have a string:

s = "this is just a sample string"

I want to obtain a list of 3 characters each:

l = ["thi", "s i", "s j", "ust", " a ", ...]


Solution 1:[1]

Don't use list for a variable name because it's a keyword in Python. Here's how you can do it:

string =  "this is just a sample string"
l = [string[i:i+3] for i in range(0,len(string),3)]
print(l)

Output:

['thi', 's i', 's j', 'ust', ' a ', 'sam', 'ple', ' st', 'rin', 'g']

Solution 2:[2]

you can use list comprehension

string = "this is just a sample string"
n = 3
[string[i:i+n] for i in range(0, len(string), n)]

output

chunks = ['thi', 's i', 's j', 'ust', ' a ', 'sam', 'ple', ' st', 'rin', 'g']

Solution 3:[3]

With more-itertools:

from more_itertools import chunked
list = [''.join(chunk) for chunk in chunked(string, 3)]

Solution 4:[4]

You can match 1-3 characters using the dot to match any character including a space and a quantifier {1,3}

import re

print(re.findall(r".{1,3}", "this is just a sample string"))

Output

['thi', 's i', 's j', 'ust', ' a ', 'sam', 'ple', ' st', 'rin', 'g']

If you don't want the single char match for 'g' then you can use .{3} instead of {1,3}

Solution 5:[5]

Using generators to split the string in fixed-size blocks. If the length of the string is not a multiple of the block's size then the "tail" it will be also be added (no information provided). If "tail" not desired check if len(string) % block_size == 0: if False then output[:-1].

import itertools as it

s = "this is just a sample string"

s = it.tee(s, 1)[0] # as generator, or just iter(s)!
out = []
for block in iter(lambda: ''.join(it.islice(s, 0, 3, None)), ''):
    out.append(block)

print(out)

or with a while loop

import itertools as it

s = "this is just a sample string"

s_iter = iter(lambda: ''.join(it.islice(s, 0, 3, None)), '')
out = []
v = is_over = next(s_iter, False)
while is_over is not False:
    out.append(v)
    v = is_over = next(s_iter, False)

print(out)

Solution 6:[6]

Here is another solution:

s = "this is just a sample string"
length =  3
lst = []
i = 0
while i < len(s):
    lst.append(s[i:i+length])
    i+=length
print(lst)

Output:

['thi', 's i', 's j', 'ust', ' a ', 'sam', 'ple', ' st', 'rin', 'g']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abhyuday Vaish
Solution 2 EL-AJI Oussama
Solution 3 Learning is a mess
Solution 4 The fourth bird
Solution 5
Solution 6 Jake Korman