split number on their counts in python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fareedcanada
    New Member
    • Feb 2024
    • 1

    split number on their counts in python

    Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16, 17 and if 11314151617 (11cnt) then should be split like 1,13,1,15,16,17

    I am trying to code like

    if linecnt == 12 :
    numList = [int(digit) for digit in str(strsplit)]
    print(numList)

    however i m getting 1,2,1,3,1,4,1,5 ,`,6 ..

    guyz any help plz..
  • dev7060
    Recognized Expert Contributor
    • Mar 2017
    • 656

    #2
    I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16, 17 and if 11314151617 (11cnt) then should be split like 1,13,1,15,16,17
    What you mean by count?

    Comment

    • Hichem
      New Member
      • Apr 2023
      • 2

      #3
      To split the number correctly based on your requirement, you should use a different approach that considers the count of digits in the number. Here's a Python function that does that:
      Code:
      def split_number(number, linecnt):
          number_str = str(number)
          result = []
          
          if linecnt == 12:
              for i in range(0, len(number_str), 2):
                  result.append(int(number_str[i:i+2]))
          elif linecnt == 11:
              i = 0
              while i < len(number_str):
                  if i == 0 or i == 2:
                      result.append(int(number_str[i]))
                      i += 1
                  else:
                      result.append(int(number_str[i:i+2]))
                      i += 2
                      
          return result
      
      # Test cases
      number1 = 121314151617
      linecnt1 = 12
      number2 = 11314151617
      linecnt2 = 11
      
      print(split_number(number1, linecnt1))  # Output: [12, 13, 14, 15, 16, 17]
      print(split_number(number2, linecnt2))  # Output: [1, 13, 1, 14, 15, 16, 17]

      Comment

      • kaleemjaan
        New Member
        • Nov 2025
        • 15

        #4
        You are converting the string into single digits, that’s why you are getting 1,2,1,3.... Instead, you should split the string in pairs when the count is 12. You can use slicing like text[i:i+2] inside a loop to get 12,13,14,15,16, 17 correctly. Learning small Python tricks like this is similar to understanding Why Choose IPTV services — simple logic can improve the overall experience and performance.

        Comment

        Working...