Split a string every nth character in Python

avatar

Borislav Hadzhiev

Last updated: Jun 23, 2022

banner

Check out my new book

Split a string every nth character in Python #

To split a string every nth character:

  1. Use a list comprehension to iterate over a range with step N.
  2. On each iteration, use string slicing to select a slice of the string.
  3. The list will contain string slices with maximum length of N.
main.py
my_str = 'abcdefgh' n = 2 my_list = [my_str[idx:idx + n] for idx in range(0, len(my_str), n)] print(my_list) # 👉️ ['ab', 'cd', 'ef', 'gh']

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 range object in the example contains the indices of the first character of each slice.

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

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

The start value is inclusive, and the stop value is exclusive (up to, but not including).

We calculate the stop index by adding 2 to the start index. The example splits the string every 2 characters.

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

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 = [my_str[idx:idx + n] for idx in range(0, len(my_str), n)] print(my_list) # 👉️ ['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 from the textwrap module.

To split a string every n characters:

  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.