Split String into Specific Length Chunks - 3 Python Examples
Split string into specific length chunks
To split a string into chunks of specific length, use List Comprehension with the string. All the chunks will be returned as an array.
We can also use a while loop to split a list into chunks of specific length.
In this tutorial, we shall learn how to split a string into specific length chunks, with the help of well detailed example Python programs.
Sample Code Snippet
Following is a quick code snippet to split a given string str
into chunks of specific length n
using list comprehension.
n = 3 # chunk length
chunks = [str[i:i+n] for i in range(0, len(str), n)]
Examples
1. Split string into chunks of length 3
In this, we will take a string str
and split this string into chunks of length 3
using list comprehension.
Python Program
str = 'CarBadBoxNumKeyValRayCppSan'
n = 3
chunks = [str[i:i+n] for i in range(0, len(str), n)]
print(chunks)
Explanation
- The string
str = 'CarBadBoxNumKeyValRayCppSan'
is defined, and the goal is to split it into chunks of lengthn = 3
. - A list comprehension is used to generate the chunks. The range function
range(0, len(str), n)
ensures that we iterate through the string in steps of 3. - In each iteration, a substring of length
n = 3
is extracted usingstr[i:i+n]
, wherei
is the current index in the string. - The result is a list of strings, where each string is a chunk of 3 characters.
Output
['Car', 'Bad', 'Box', 'Num', 'Key', 'Val', 'Ray', 'Cpp', 'San']
The string is split into a list of strings with each of the string length as specified, i.e., 3. You can try with different length and different string values.
2. Split string by length
In this example we will split a string into chunks of length 4. Also, we have taken a string such that its length is not exactly divisible by chunk length. In that case, the last chunk contains characters whose count is less than the chunk size we provided.
Python Program
str = 'Welcome to Python Examples'
n = 4
chunks = [str[i:i+n] for i in range(0, len(str), n)]
print(chunks)
Explanation
- The string
str = 'Welcome to Python Examples'
is defined, and the goal is to split it into chunks of lengthn = 4
. - A list comprehension is used to generate the chunks. The range function
range(0, len(str), n)
ensures that we iterate through the string in steps of 4. - In each iteration, a substring of length
n = 4
is extracted usingstr[i:i+n]
, wherei
is the current index in the string. - The result is a list of strings, where each string is a chunk of 4 characters.
Output
['Welc', 'ome ', 'to P', 'ytho', 'n Ex', 'ampl', 'es']
3. Split string with 0 chunk length
In this example, we shall test a negative scenario with chink size of 0, and check the output. range() function raises ValueError if zero is given for its third argument.
Python Program
str = 'Welcome to Python Examples'
#chunk size
n = 0
chunks = [str[i:i+n] for i in range(0, len(str), n)]
print(chunks)
Explanation
- The string
str = 'Welcome to Python Examples'
is defined, and the goal is to split it into chunks of sizen = 0
. - The list comprehension
[str[i:i+n] for i in range(0, len(str), n)]
attempts to create chunks, but sincen
is set to 0, it will result in an invalid slice. - When
n = 0
, attempting to slice the string in this manner will cause an infinite loop or error, as a slice size of 0 is not valid. This will likely raise aValueError
or cause unexpected behavior.
Output
Traceback (most recent call last):
File "example1.py", line 4, in <module>
chunks = [str[i:i+n] for i in range(0, len(str), n)]
ValueError: range() arg 3 must not be zero
Chunk length must not be zero, and hence we got a ValueError for range().
4. Split string into chunks using While loop
In this example, we will split string into chunks using Python While Loop.
Python Program
str = 'Welcome to Python Examples'
n = 5
chunks = []
i = 0
while i < len(str):
if i+n < len(str):
chunks.append(str[i:i+n])
else:
chunks.append(str[i:len(str)])
i += n
print(chunks)
Explanation
- The string
str = 'Welcome to Python Examples'
is defined, and the goal is to split it into chunks of sizen = 5
. - An empty list
chunks
is initialized to store the split string chunks. - A
while
loop is used to iterate over the string, starting from indexi = 0
. The loop runs untili
reaches the length of the string. - Inside the loop, if there are enough characters remaining in the string (
i + n < len(str)
), it adds a chunk of sizen
fromstr[i:i+n]
to thechunks
list. - If there aren't enough characters left, it adds the remaining part of the string starting from index
i
to the end usingstr[i:len(str)]
. - The value of
i
is incremented byn
in each iteration to move the starting index of the next chunk. - The output is the list
['Welco', 'me to', ' Pyth', 'on Ex', 'ample', 's']
, where the string has been split into 5-character chunks.
Output
['Welco', 'me to', ' Pyth', 'on Ex', 'ample', 's']
Summary
In this tutorial of Python Examples, we learned how to split string by length in Python with the help of well detailed examples.