Python – Split Numeric String into K digit integers

When working with numeric strings, you may need to split them into equal-sized chunks and convert each chunk to an integer. This can be achieved using simple iteration, slicing, and the int() method.

Example

Below is a demonstration of splitting a numeric string into K-digit integers ?

my_string = '69426874124863145'

print("The string is :")
print(my_string)

K = 4
print("The value of K is")
print(K)

my_result = []
for index in range(0, len(my_string), K):
    my_result.append(int(my_string[index : index + K]))

print("The resultant list is :")
print(my_result)

print("The resultant list after sorting is :")
my_result.sort()
print(my_result)

Output

The string is :
69426874124863145
The value of K is
4
The resultant list is :
[6942, 6874, 1248, 6314, 5]
The resultant list after sorting is :
[5, 1248, 6314, 6874, 6942]

How It Works

The algorithm uses string slicing with a step of K characters:

  • A numeric string is defined and displayed on the console.

  • The value of K (chunk size) is defined and displayed.

  • An empty list is created to store the results.

  • The string is iterated in steps of K, extracting substrings of length K.

  • Each substring is converted to an integer using int() and appended to the list.

  • The final chunk may have fewer than K digits if the string length is not divisible by K.

  • The list is optionally sorted and displayed.

Alternative Using List Comprehension

my_string = '69426874124863145'
K = 4

# One-liner using list comprehension
my_result = [int(my_string[i:i+K]) for i in range(0, len(my_string), K)]
print("Result:", my_result)
Result: [6942, 6874, 1248, 6314, 5]

Conclusion

Use range(0, len(string), K) with string slicing to split numeric strings into K-digit chunks. The last chunk may contain fewer digits if the string length isn't divisible by K.

Updated on: 2026-03-26T01:42:22+05:30

429 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements