在python中用字符串交换字母

Nea*_*ang 7 python

我试图切换字符串中的第一个字符并将其移动到字符串的末尾.它需要重复旋转n次.例如,rotateLeft(hello,2)=llohe.

我试过了

def rotateLeft(str,n):
    rotated=""
    rotated=str[n:]+str[:n]
    return rotated 
Run Code Online (Sandbox Code Playgroud)

这是对的吗?如果删除最后一个字符并将其移到字符串的前面,你会怎么做?

Tim*_*ker 16

你可以缩短它

def rotate(strg,n):
    return strg[n:] + strg[:n]
Run Code Online (Sandbox Code Playgroud)

并简单地使用负指数"向右"旋转:

>>> 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' 
Run Code Online (Sandbox Code Playgroud)

如果您想在超过琴弦长度后继续旋转,请使用

def rotate(strg,n):
    n = n % len(strg)
    return strg[n:] + strg[:n]
Run Code Online (Sandbox Code Playgroud)

所以你得到了

>>> rotate("hello", 1)
'elloh'
>>> rotate("hello", 6)
'elloh'
Run Code Online (Sandbox Code Playgroud)