Reputation: 37
How should I change the order of a string?
a = 'abcdefg'
and I want to put the last character of the string at beginning every time when I iterate through the string
a = 'gabcdef'
a = 'fgabcde`
etc
Upvotes: 0
Views: 378
Reputation: 614
You could add something like a = a[-1] + a[:-1]
a = 'abcdefg'
for i in range(len(a)):
a = a[-1] + a[:-1]
print(a)
>>gabcdef
>>fgabcde
>>efgabcd
>>defgabc
>>cdefgab
>>bcdefga
>>abcdefg
Upvotes: 0
Reputation: 4075
You could use a deque
as an alternative to slicing:
from collections import deque
a = 'abcdefg'
d = deque(a)
for _ in range(len(a)):
d.rotate()
print(''.join(d))
Output:
gabcdef
fgabcde
efgabcd
defgabc
cdefgab
bcdefga
abcdefg
Upvotes: 0