-1

I'm trying to run a script that takes a long series of numbers and checks them 4 at a time, so I'm using a for in range(0, len(stringOfDigits), 4): checking the string of numbers using the variable of the loop:

for i in range(0, len(stringOfDigits), 4):
    currFour = stringOfDigits[i:4]
    print("Current 4 being checked are")
    print(currFour)

But if I try to run it, it just pastes empty rows and exit the script like it's done.

What's the problem? Do strings accept variables when substringing? If not, what can I do to achieve the result I want?

K3nzie
  • 445
  • 1
  • 7
  • 20
  • 1
    Do `currFour = digits[i:i+4]`. – Arkistarvh Kltzuonstev May 01 '19 at 16:39
  • @ArkistarvhKltzuonstev Any particular reason for that? I mean, isn't it technically the same? Why you need to use the variable for both of the range limits? – K3nzie May 01 '19 at 16:42
  • No, they aren't same. If you want to check `i`th position to the next four positions, you need `digits[i:i+4]`, but if you need to check `i`th position to only the `4`th item of `digits`, then you need `digits[i:4]`. – Arkistarvh Kltzuonstev May 01 '19 at 16:45

1 Answers1

1

You need following inside loop:

currFour = stringOfDigits[i:i+4]

instead of:

currFour = stringOfDigits[i:4]

With currFour = stringOfDigits[i:4], first loop works, but successive loopings fail. This is because: One case in the second iteration when i becomes 4, stringOfDigits[i:4] -> stringOfDigits[4:4] (where you ideally needed a slice of [4:8]) which returns empty string and so on for remaining loopings.

Austin
  • 25,759
  • 4
  • 25
  • 48