Python – Split string into specific length chunks

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)
Run Code Copy

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)
Run Code Copy

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)
Run Code Copy

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)
Run Code Copy

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.

Related Tutorials

Code copied to clipboard successfully 👍