Python – Split Numeric String into K digit integers


When it is required to split a numeric string into K digit integers, a simple iteration, the ‘int’ method and the ‘append’ methods are used.

Example

Below is a demonstration of the same −

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]

Explanation

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

  • The value of K is defined and is displayed on the console.

  • An empty list is defined.

  • The list is iterated over, and the elements in the string within a specific range are converted into an integer.

  • This value is appended to the empty list.

  • This is displayed as the output on the console.

  • This list is sorted again and is displayed on the console.

Updated on: 13-Sep-2021

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements