Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
