string manipulation
number splitting
programming
coding techniques
data processing

Splitting a string / number every Nth Character / Number?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Splitting text or digits into fixed-size chunks is a common task in formatting, parsing, and data cleaning. The core operation is simple slicing, but the details matter when numbers, leading zeros, or incomplete final chunks are involved. The safest approach is to treat the input as a sequence and make the chunking rules explicit.

Python: Chunk a String Every n Characters

In Python, slicing with a step through the string is the cleanest solution.

python
1def chunk_string(value: str, size: int) -> list[str]:
2    if size <= 0:
3        raise ValueError("size must be positive")
4    return [value[i:i + size] for i in range(0, len(value), size)]
5
6print(chunk_string("ABCDEFGHIJ", 3))

Output:

python
['ABC', 'DEF', 'GHI', 'J']

This preserves the final partial chunk instead of discarding it.

Split Digits by Treating Them as Text

If the input is conceptually a number but formatting matters, convert it to a string first. That is essential when leading zeros are meaningful.

python
1def chunk_digits(value: str, size: int) -> list[str]:
2    if not value.isdigit():
3        raise ValueError("value must contain digits only")
4    return [value[i:i + size] for i in range(0, len(value), size)]
5
6print(chunk_digits("0012345678", 2))

If you used the integer 12345678, the leading zeros would already be lost.

Join Chunks with a Separator

A common follow-up is converting the chunks into a formatted display string.

python
1digits = "1234567890"
2parts = [digits[i:i + 3] for i in range(0, len(digits), 3)]
3formatted = "-".join(parts)
4
5print(formatted)

That pattern is useful for serial numbers, grouped identifiers, and readable debug output.

JavaScript Version

JavaScript uses the same basic idea with slice.

javascript
1function chunkString(value, size) {
2  if (size <= 0) {
3    throw new Error("size must be positive");
4  }
5
6  const result = [];
7  for (let i = 0; i < value.length; i += size) {
8    result.push(value.slice(i, i + size));
9  }
10  return result;
11}
12
13console.log(chunkString("ABCDEFGHIJ", 4));

Again, treat numbers as strings if the formatting of individual digits matters.

C# Version

A small iterator is a clean way to expose chunking in C#.

csharp
1using System;
2using System.Collections.Generic;
3
4static IEnumerable<string> Chunk(string value, int size)
5{
6    if (size <= 0) throw new ArgumentOutOfRangeException(nameof(size));
7
8    for (int i = 0; i < value.Length; i += size)
9    {
10        yield return value.Substring(i, Math.Min(size, value.Length - i));
11    }
12}
13
14foreach (var part in Chunk("ABCDEFGHIJ", 3))
15{
16    Console.WriteLine(part);
17}

This is especially useful when another component will consume the chunks one by one.

Decide What to Do with an Uneven Tail

Most chunking functions keep the last short segment. That is often the right default, but some applications require exact-length groups.

python
1def chunk_exact(value: str, size: int) -> list[str]:
2    if size <= 0:
3        raise ValueError("size must be positive")
4    if len(value) % size != 0:
5        raise ValueError("input length must be divisible by size")
6    return [value[i:i + size] for i in range(0, len(value), size)]
7
8print(chunk_exact("ABCDEF", 2))

If exact chunk length matters, fail early rather than silently truncating or padding.

Use Iterators for Very Large Inputs

For large strings, a generator avoids building the entire list up front.

python
1def iter_chunks(value: str, size: int):
2    if size <= 0:
3        raise ValueError("size must be positive")
4    for i in range(0, len(value), size):
5        yield value[i:i + size]
6
7for part in iter_chunks("ABCDEFGHIJ", 3):
8    print(part)

That can reduce memory use when you stream chunks into another process.

Common Pitfalls

The biggest mistake is chunking numeric types directly when leading zeros matter. Once the value becomes an integer, that formatting information is gone.

Another issue is forgetting to validate the chunk size. A size of zero or a negative value should be rejected immediately.

Developers also sometimes assume the last chunk must be full-sized without documenting that rule. If exact-length chunks are required, the function should enforce it explicitly.

Summary

  • Split fixed-size groups with slicing and a step of n.
  • Treat numbers as strings when exact digit formatting matters.
  • Decide whether a short final chunk is allowed or should raise an error.
  • Use iterators when the input is large and you do not need all chunks at once.
  • Validate the chunk size so invalid input fails clearly.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions