您可以将其缩短为
def rotate(strg,n):
return strg[n:] + strg[:n]
并简单地使用负索引来“向右”旋转:
>>> rotate("hello", 2)
'llohe'
>>> rotate("hello", -1)
'ohell'
>>> rotate("hello", 1)
'elloh'
>>> rotate("hello", 4)
'ohell'
>>> rotate("hello", -3)
'llohe'
>>> rotate("hello", 6) # same with -6: no change if n > len(strg)
'hello'
如果即使在超过字符串长度后仍要保持旋转,请使用
def rotate(strg,n):
n = n % len(strg)
return strg[n:] + strg[:n]
所以你得到
>>> rotate("hello", 1)
'elloh'
>>> rotate("hello", 6)
'elloh'