swap letters in a string in python

后端 未结 3 918
广开言路
广开言路 2021-01-12 10:43

I am trying to switch the first character in a string and move it to the end of the string. It needs to repeat the rotation a number of n times. For example, rotateLef

3条回答
  •  隐瞒了意图╮
    2021-01-12 10:54

    You can shorten it to

    def rotate(strg,n):
        return strg[n:] + strg[:n]
    

    and simply 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)  # same with -6: no change if n > len(strg)
    'hello' 
    

    If you want to keep rotating even after exceeding the length of the string, 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'
    

提交回复
热议问题