Explain Codes LogoExplain Codes Logo

Split string every nth character

python
functions
generators
list-comprehension
Nikita BarsukovbyNikita Barsukov·Oct 14, 2024
TLDR

Cut the chatter, dive in! To slice a string into chunks of n letters, use some list comprehension magic:

chunks = [s[i:i+n] for i in range(0, len(s), n)]

Here's how it works:

s = "stackoverflow" n = 3 print([s[i:i+n] for i in range(0, len(s), n)]) # ['sta', 'cko', 'ver', 'flo', 'w']

This genius line of code will gift you an array of substrings, each of n length, from string s. And don't worry, it also happens to handle cases where the string length is not divisible evenly by n.

Slice it like a pro!

Maybe you want to deal with non-evenly divisible strings more explicitly, or perhaps you're just a fan of pure one-liners. Here you go:

from textwrap import wrap wrapped_chunks = wrap(s, n) # If you need Python to tuck you in at night, this is it

Or venture out into the wilds with some regular expressions:

import re regex_chunks = re.findall('.{1,'+ str(n) +'}', s) # If it scares you just a bit, you know it's good regex

Big strings? Generators to the rescue!

When long strings enter the game or when every CPU cycle counts, generators with yield are a godsend. They process chunks as needed, using just a fraction of memory:

def cut_the_pizza(seq, n): # Because slicing pizzas is serious business while seq: yield seq[:n] seq = seq[n:]

Try it on your mama's special 'pepperoni and olive' pizza recipe:

pizza = 'PPEEPERRNOONIAONDDVOLILIVEEE' slice_size = 5 print(list(cut_the_pizza(pizza, slice_size))) # ['PPEEP', 'ERRNO', 'ONIAD', 'DVOLI', 'LIVEE']

When zip meets iter

The less-known but incredibly smart way is to use iter and zip to create pairs of characters and then join them:

it = iter(s) print([''.join(ch) for ch in zip(*[it]*n)]) # It's like playing Tetris

You will appreciate this trick next time you need to beat a Sudoku or a Crossword. It's a clear example of Pythonic elegance.

Tailor your code

When choosing the best approach, consider the context and requirements of your application. If you need the simplest possible solution, the list comprehension approach is your friend. For larger datasets or speed requirements, consider the generator or re.finditer. Make your code the smartest guy in the room.