Rotating strings in Python

Here is one way:

def rotate(strg, n):
    return strg[n:] + strg[:n]

rotate('HELLO', -1)  # 'OHELL'

Alternatively, collections.deque ("double-ended queue") is optimised for queue-related operations. It has a dedicated rotate() method:

from collections import deque

items = deque('HELLO')
items.rotate(1)

''.join(items)  # 'OHELL'

You can slice and add strings:

>>> s = 'HELLO'
>>> s[-1] + s[:-1]
'OHELL'

This gives you the last character:

>>> s[-1]
'O'

and this everything but the last:

>>> s[:-1]
'HELL'

Finally, add them with +.


Here is what I use to rotate strings in Python3:

To rotate left by n:

def leftShift(text,n):
    return text[n:] + text[:n]

To rotate right by n:

def rightShift(text,n):
    return text[-n:] + text[:-n]

Here is a simple way of looking at it...

s = 'HELLO'
for r in range(5):
    print(s[r:] + s[:r])


HELLO
ELLOH
LLOHE
LOHEL
OHELL