Reputation: 43
I'm attempting to write some code as practice for python. After the user inputs a string and a number that is a factor of the length of the string, the output should be the reverse of the string split up into segments equal to the inputted number. My issue is that the output is cut short, which I believe is a problem caused by the condition of my for loop.
def reverse_and_slice(string, k):
i=0
n=len(string)
j=0
revstring=string[::-1]
finalstring=''
for i in range(n//k):
finalstring+=revstring[j:(i+1)*k] + ' '
j+=(i+1)*k
i+=1
print(finalstring)
I am trying to accomplish this using a for loop. 123456789 should print as 987 654 321. However, it is currently printing as 987 654, without the last three digits. Longer inputs are similarly cut short with only two segments of length k.
Upvotes: 2
Views: 68
Reputation: 1039
Your loop iterate correct amount of times. You can simply check it by printing i
in the loop. Problem is with j
. In the last iteration, it is equal to 9, so revstring[9:9]
is empty. And this is caused by +
before =
: j+=(i+1)*k
You are incrementing j
instead of changing value.
def reverse_and_slice(string, k):
i=0
n=len(string)
j=0
revstring=string[::-1]
finalstring=''
for i in range(n//k):
finalstring+=revstring[j:(i+1)*k] + ' '
j = (i+1)*k
i+=1 # this line is also not needed
print(finalstring)
Upvotes: 1