You can shorten it to
def rotate(strg,n): return strg[n:] + strg[:n]
and just use negative indices to rotate to the right:
>>> rotate("hello", 2) 'llohe' >>> rotate("hello", -1) 'ohell' >>> rotate("hello", 1) 'elloh' >>> rotate("hello", 4) 'ohell' >>> rotate("hello", -3) 'llohe' >>> rotate("hello", 6)
If you want to keep spinning even after exceeding the string length, use
def rotate(strg,n): n = n % len(strg) return strg[n:] + strg[:n]
so you get
>>> rotate("hello", 1) 'elloh' >>> rotate("hello", 6) 'elloh'
source share