0

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
2
  • Updated: a=a[-1]+a[:-1] Commented Jun 11, 2020 at 16:46
  • 2
    @PrateekDewan, this will give the wrong output Commented Jun 11, 2020 at 16:47

3 Answers 3

1

You can try this:-

a = a[-1] + a[:-1]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.