Reputation: 99
I need help with writing a loop that can slice through a string, taking away the first and last character. I understand that the slice [0:-1] can target those two positions, but I need a way for it to iterate through the whole string. Here is a little snippet into what the output would ideally look like:
Input (min for length is 3) :
string = 'ABCDEFGHI'
Output:
['ABCDEFGHI', 'BCDEFGH', 'CDEFG']
I would be grateful for any guidance/advice!
Upvotes: 1
Views: 145
Reputation: 59444
Try this:
>>> [string[i:len(string)-i] for i in range(3)]
['ABCDEFGHI', 'BCDEFGH', 'CDEFG']
Upvotes: 4
Reputation: 451
Here's a function you can use:
def foo(string, limit=None):
output = [string]
i = 0
if limit == None:
while i < len(string) / 2 - 1:
output.append(output[-1][1:-1])
i += 1
else:
while i < limit - 1:
output.append(output[-1][1:-1])
i += 1
return output
The second parameter can be used to set a limit to the length of the array. It is optional.
Upvotes: 1