在python中的字符串中交换字母
问题内容:
我正在尝试切换字符串中的第一个字符并将其移到字符串的末尾。它需要重复旋转n次。例如,rotateLeft(hello,2)=llohe
。
我试着做
def rotateLeft(str,n):
rotated=""
rotated=str[n:]+str[:n]
return rotated
这是正确的吗,如果它删除了最后一个字符并将其移到字符串的开头,您将如何处理?
问题答案:
您可以将其缩短为
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'