Python中从右侧按固定间隔拆分字符串的错误排查求助
Hey Joe, let's break down why your right-to-left slicing code is returning an empty string instead of the expected 'ab'!
What's Going Wrong
Your current code uses range(n, 0, -3) which generates the values 5 and 2 for the string "abcde" (length 5). When i=2, the slice string[i-3:i] becomes string[-1:2].
In Python, slicing follows the rule: if the start index is greater than the end index (here, -1 translates to index 4, which is larger than 2), the result is an empty string—since there's no valid left-to-right range to extract characters from.
Quick Fix: Clamp the Start Index
The simplest solution is to ensure your start index never drops below 0 using max(0, i-3). This way, when i-3 is negative, we start slicing from the beginning of the string instead:
string = "abcde" n = len(string) slices = [string[max(0, i-3):i] for i in range(n, 0, -3)] print(slices) # Output: ['cde', 'ab']
Alternative Approach: Reverse and Reuse Working Logic
Since you already have a working left-to-right slicing method, you can leverage that by reversing the string first, applying your existing code, then reversing each slice and the final list to get the right-to-left split:
string = "abcde" reversed_str = string[::-1] # Use your working left-to-right slicing on the reversed string temp_slices = [reversed_str[i:i+3] for i in range(0, len(reversed_str), 3)] # Reverse each slice and flip the list order slices = [s[::-1] for s in temp_slices][::-1] print(slices) # Output: ['cde', 'ab']
Key Takeaway
The core issue was that your original slice attempted to go from a higher index to a lower one (due to the negative start index), which doesn't work with Python's default left-to-right slicing direction. By clamping the start index or using the reverse-and-reverse-back trick, you get the expected result.
内容的提问来源于stack exchange,提问作者Joe

