Alex Hu
Alex Hu

Reputation: 37

#Python string slicing and change the order of a string

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

Answers (3)

Kunal Shah
Kunal Shah

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

Terry Spotts
Terry Spotts

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

Dhaval Taunk
Dhaval Taunk

Reputation: 1672

You can try this:-

a = a[-1] + a[:-1]

Upvotes: 1

Related Questions