Split a string into fixed size chunks in Python

avatar

Borislav Hadzhiev

Last updated: Jun 24, 2022

banner

Photo from Unsplash

Split a string into fixed size chunks in Python #

To split a string into fixed size chunks:

  1. Declare a variable that stores an empty list.
  2. Iterate over a range of the string's length with a step.
  3. On each iteration, append a string of length N to the list.
main.py
my_str = 'abcdefgh' my_list = [] n = 2 for i in range(0, len(my_str), n): my_list.append(my_str[i:i+n]) print(my_list) # 👉️ ['ab', 'cd', 'ef', 'gh'] # -------------------------------------------- # using list comprehension my_list_2 = [my_str[i:i+n] for i in range(0, len(my_str), n)] print(my_list_2) # 👉️ ['ab', 'cd', 'ef', 'gh']

We used the range class to get a range of indices that represent the first character in each chunk.

main.py
my_str = 'abcdefgh' my_list = [] n = 2 # 👇️ [0, 2, 4, 6] print(list(range(0, len(my_str), n)))

The range class is commonly used for looping a specific number of times in for loops and takes the following parameters:

NameDescription
startAn integer representing the start of the range (defaults to 0)
stopGo up to, but not including the provided integer
stepRange will consist of every N numbers from start to stop (defaults to 1)

The syntax for string slicing is my_str[start:stop:step].

main.py
my_str = 'abcdefgh' my_list = [] n = 2 for i in range(0, len(my_str), n): my_list.append(my_str[i:i+n]) print(my_list) # 👉️ ['ab', 'cd', 'ef', 'gh']

Note that the start index is inclusive, whereas the stop index is exclusive.

On each iteration, we get the start index from the current item in the range, and calculate the stop index by adding the start index to the desired chunk length.

Alternatively, you can use a list comprehension.

main.py
my_str = 'abcdefgh' n = 2 my_list_2 = [my_str[i:i+n] for i in range(0, len(my_str), n)] print(my_list_2) # 👉️ ['ab', 'cd', 'ef', 'gh']

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

This solution is the single-line version of the first code snippet that used a for loop.

If the string has a length that is an odd number, the last item in the list will contain less characters.

main.py
my_str = 'abcdefghi' n = 2 my_list_2 = [my_str[i:i+n] for i in range(0, len(my_str), n)] print(my_list_2) # 👉️ ['ab', 'cd', 'ef', 'gh', 'i']

You can also use a while loop to split a string every nth character.

main.py
my_str = 'abcdefghi' my_str_copy = my_str my_list = [] n = 2 while my_str_copy: my_list.append(my_str_copy[:n]) my_str_copy = my_str_copy[n:] # 👇️ ['ab', 'cd', 'ef', 'gh', 'i'] print(my_list)

We declared a second variable that stores the exact same string.

On each iteration in the while loop, we append the first n characters of the copied string to the list and remove the first n characters from the copied string.

You can also use the wrap() method to split a string into fixed size chunks.

To split a string into fixed size chunks:

  1. Import the wrap() method from the textwrap module.
  2. Pass the string and the max width of each slice to the method.
  3. The wrap() method will split the string into a list with items of max length N.
main.py
from textwrap import wrap my_str = 'abcdefgh' n = 2 my_list = wrap( my_str, n, drop_whitespace=False, break_on_hyphens=False ) # 👇️ ['ab', 'cd', 'ef', 'gh'] print(my_list)

The textwrap.wrap method will split the string into a list, so that every list item is at most N characters long.

We set the drop_whitespace keyword argument to False because the default behavior of the method is to remove whitespace.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.