Split String of Size N in Python

Splitting a string into chunks of equal size is a common task in Python programming. This involves breaking down a string into smaller substrings, each containing exactly n characters (except possibly the last chunk).

For example, if we have s = "abcdefghijklmn" and n = 4, the output will be ['abcd', 'efgh', 'ijkl', 'mn'].

Using a While Loop

The most straightforward approach uses a while loop to iterate through the string and extract chunks ?

def split_string(s, n):
    i = 0
    chunks = []
    while i < len(s):
        chunks.append(s[i:i+n])
        i += n
    return chunks

# Example usage
text = "abcdefghijklmn"
chunk_size = 4
result = split_string(text, chunk_size)
print(result)
['abcd', 'efgh', 'ijkl', 'mn']

Using List Comprehension

A more Pythonic approach uses list comprehension with the range() function ?

def split_string_compact(s, n):
    return [s[i:i+n] for i in range(0, len(s), n)]

# Example usage
text = "abcdefghijklmn"
chunk_size = 4
result = split_string_compact(text, chunk_size)
print(result)
['abcd', 'efgh', 'ijkl', 'mn']

Using textwrap Module

Python's textwrap module provides a built-in solution for this problem ?

import textwrap

def split_with_textwrap(s, n):
    return textwrap.wrap(s, n)

# Example usage
text = "abcdefghijklmn"
chunk_size = 4
result = split_with_textwrap(text, chunk_size)
print(result)
['abcd', 'efgh', 'ijkl', 'mn']

Comparison

Method Readability Performance Best For
While Loop Good Fast Learning/Understanding
List Comprehension Excellent Fastest Pythonic code
textwrap Good Good Text processing tasks

Conclusion

Use list comprehension for the most Pythonic and efficient solution. The while loop approach is great for understanding the logic, while textwrap.wrap() is ideal when working with text processing applications.

Updated on: 2026-03-25T10:17:16+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements