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'

Leave a Comment

deneme bonusu veren sitelerbahis casino