Hướng dẫn python rotate string

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a string of size n, write functions to perform following operations on string.

    1. Left (Or anticlockwise) rotate the given string by d elements (where d <= n).
    2. Right (Or clockwise) rotate the given string by d elements (where d <= n).

    Examples:

    Input : s = "GeeksforGeeks"
            d = 2
    Output : Left Rotation  : "eksforGeeksGe" 
             Right Rotation : "ksGeeksforGee"  
    
    
    Input : s = "qwertyu" 
            d = 2
    Output : Left rotation : "ertyuqw"
             Right rotation : "yuqwert"

    Method 1: We have existing solution for this problem please refer Left Rotation and Right Rotation of a String link. We will solve this problem quickly in python using String Slicing. Approach is very simple,

    1. Separate string in two parts first & second, for Left rotation Lfirst = str[0 : d] and Lsecond = str[d :]. For Right rotation Rfirst = str[0 : len(str)-d] and Rsecond = str[len(str)-d : ].
    2. Now concatenate these two parts second + first accordingly.

    Implementation:

    Python3

    def rotate(input,d):

        Lfirst = input[0 : d]

        Lsecond = input[d :]

        Rfirst = input[0 : len(input)-d]

        Rsecond = input[len(input)-d : ]

        print ("Left Rotation : ", (Lsecond + Lfirst) )

        print ("Right Rotation : ", (Rsecond + Rfirst))

    if __name__ == "__main__":

        input = 'GeeksforGeeks'

        d=2

        rotate(input,d)

    Output:

    Left Rotation  : eksforGeeksGe 
    Right Rotation : ksGeeksforGee

    Method 2: We use extended string to rotate the string. We will solve this problem quickly in python by slicing extended string. Approach is very simple,

    Use extended string Extend_str, for Left rotation Lfirst = Extended_str[n : l1+n] . For Right rotation Rfirst = str[l1-n : l2-n].
    Now print this string. 

    Implementation:

    Python3

    def rotate(str1,n):

        temp = str1 + str1

        l1 = len(str1)

        l2 = len(temp)

        Lfirst = temp[n  : l1+n]

        Lfirst = temp[l1-n : l2-n]

        print ("Left Rotation : ", Lfirst)

        print ("Right Rotation : ", Lfirst )

    if __name__ == "__main__":

        input = 'GeeksforGeeks'

        d=2

        rotate(input,d)

    Output

    Left Rotation :  ksGeeksforGee
    Right Rotation :  ksGeeksforGee

    I was trying to make the string HELLO to OHELL in Python. But couldn't get any way to rotate it without working with loops. How to code for it in just 1-2 lines so that I could get the desired pattern?

    asked Feb 4, 2018 at 10:55

    2

    Here is one way:

    def rotate(strg, n):
        return strg[n:] + strg[:n]
    
    rotate('HELLO', -1)  # 'OHELL'
    

    Alternatively, collections.deque ("double-ended queue") is optimised for queue-related operations. It has a dedicated rotate() method:

    from collections import deque
    
    items = deque('HELLO')
    items.rotate(1)
    
    ''.join(items)  # 'OHELL'
    

    answered Feb 4, 2018 at 11:06

    Hướng dẫn python rotate string

    jppjpp

    151k31 gold badges256 silver badges317 bronze badges

    1

    You can slice and add strings:

    >>> s = 'HELLO'
    >>> s[-1] + s[:-1]
    'OHELL'
    

    This gives you the last character:

    >>> s[-1]
    'O'
    

    and this everything but the last:

    >>> s[:-1]
    'HELL'
    

    Finally, add them with +.

    answered Feb 4, 2018 at 10:58

    Mike MüllerMike Müller

    79k18 gold badges157 silver badges159 bronze badges

    2

    Here is what I use to rotate strings in Python3:

    To rotate left by n:

    def leftShift(text,n):
        return text[n:] + text[:n]
    

    To rotate right by n:

    def rightShift(text,n):
        return text[-n:] + text[:-n]
    

    answered Mar 18, 2020 at 23:50

    Clayton C.Clayton C.

    8611 gold badge8 silver badges16 bronze badges

    Here is a simple way of looking at it...

    s = 'HELLO'
    for r in range(5):
        print(s[r:] + s[:r])
    
    
    HELLO
    ELLOH
    LLOHE
    LOHEL
    OHELL
    

    answered Aug 30, 2019 at 14:28

    KonchogKonchog

    1,79018 silver badges21 bronze badges

    I would agree with Mike Müller's answer:

    s = 'HELLO'
    s = s[-1] + s[:-1]
    

    I would like to share another way of looking at s[:-1]

    s[0:-1]
    

    This means that it is starting from the start and including everything except for s[-1]. I hope this helped.

    answered Mar 16, 2019 at 20:59

    Not the answer you're looking for? Browse other questions tagged python string or ask your own question.