Open In App

Divide String into Equal K chunks – Python

Last Updated : 11 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task is to split the string into smaller parts, or “chunks,” such that each chunk has exactly k characters. If the string cannot be perfectly divided, the last chunk will contain the remaining characters.

Using List Comprehension

List comprehension allows for creating a new list by applying an expression to each element in an iterable. It combines the process of looping and conditional filtering into a single, concise line of code.

Python
s = "abcdefghij"
k = 3
chunks = [s[i:i+k] for i in range(0, len(s), k)]

print(chunks)

Output
['abc', 'def', 'ghi', 'j']

Explanation:

  • list comprehension iterates over the string s with a step size of k (3), creating substrings of length k.
  • Each substring is sliced from the string and added to the list chunks, resulting in chunks of the string: ['abc', 'def', 'ghi', 'j'].

Using a For Loop

for loop iterates through the string s in steps of size k, extracting substrings from s[i:i+k]. Each substring is appended to the chunks list, creating a collection of chunks of length k.

Python
s = "abcdefghij"
k = 3
chunks = []
for i in range(0, len(s), k):
    chunks.append(s[i:i+k])

print(chunks)

Output
['abc', 'def', 'ghi', 'j']

Explanation:

  • for loop iterates through the s string in steps of k (3), extracting substrings of length k.
  • Each substring is appended to the chunks list, resulting in ['abc', 'def', 'ghi', 'j']

Using textwrap.wrap()

textwrap.wrap() function splits the s into substrings of a specified maximum width (k). It returns a list of these substrings, each having a length of up to k characters.

Python
import textwrap

s = "abcdefghij"
k = 3
chunks = textwrap.wrap(s, k)

print(chunks)

Output
['abc', 'def', 'ghi', 'j']

Explanation:

  • textwrap.wrap() function divides the s into substrings of up to k characters.
  • It returns a list chunks containing the wrapped substrings, resulting in ['abc', 'def', 'ghi', 'j'].

Using itertools.islice()

itertools.islice() function slices the s into chunks of size k by iterating over the string in steps of k. It returns an iterator that produces these chunks, which can be converted to a list for the final result.

Python
from itertools import islice

s = "abcdefghij"
k = 3
chunks = [''.join(chunk) for chunk in zip(*[iter(s)]*k)]

print(chunks)

Output
['abc', 'def', 'ghi']

Explanation:

  • zip(*[iter(s)]*k) creates an iterator that groups the string s into chunks of size k by iterating over s and creating tuples of characters.
  • ''.join(chunk) joins each tuple of characters into a string, resulting in a list of chunks like ['abc', 'def', 'ghi']


Next Article
Practice Tags :

Similar Reads