String slicing in Python to rotate a string

String rotation involves moving characters from one end of a string to the other. Python's string slicing makes this operation simple and efficient. We can rotate strings in two directions: left rotation (anticlockwise) and right rotation (clockwise).

Understanding String Rotation

Given a string and a rotation distance d:

  • Left Rotation: Move first d characters to the end
  • Right Rotation: Move last d characters to the beginning

Example

Input: string = "pythonprogram"
d = 2
Output: Left Rotation: thonprogrampy
        Right Rotation: ampythonprogr

Algorithm

The algorithm uses string slicing to split and recombine the string:

Step 1: Take input string and rotation distance d
Step 2: For left rotation: split at position d, then concatenate second part + first part
Step 3: For right rotation: split at position (length - d), then concatenate second part + first part

Implementation

def rotate_string(text, d):
    # Left rotation: move first d characters to end
    left_first = text[0:d]
    left_second = text[d:]
    left_rotation = left_second + left_first
    
    # Right rotation: move last d characters to beginning
    right_first = text[0:len(text)-d]
    right_second = text[len(text)-d:]
    right_rotation = right_second + right_first
    
    print("Original String:", text)
    print("Left Rotation:", left_rotation)
    print("Right Rotation:", right_rotation)

# Example usage
text = "pythonprogram"
d = 2
rotate_string(text, d)
Original String: pythonprogram
Left Rotation: thonprogrampy
Right Rotation: ampythonprogr

Alternative Approach Using Modulo

To handle cases where d is greater than string length ?

def rotate_string_safe(text, d):
    n = len(text)
    # Handle cases where d > n
    d = d % n
    
    # Left rotation
    left_rotation = text[d:] + text[:d]
    
    # Right rotation  
    right_rotation = text[-d:] + text[:-d]
    
    return left_rotation, right_rotation

# Example with different rotation values
text = "python"
for d in [2, 4, 8]:  # 8 > length of string
    left, right = rotate_string_safe(text, d)
    print(f"d={d}: Left='{left}', Right='{right}'")
d=2: Left='thonpy', Right='onpyth'
d=4: Left='onpyth', Right='thonpy'  
d=8: Left='thonpy', Right='onpyth'

Comparison of Approaches

Method Handles d > n Code Complexity Best For
Basic slicing No Simple Known small rotations
Modulo + slicing Yes Slightly complex Any rotation distance

Conclusion

String rotation using slicing is efficient and readable in Python. Use modulo operator to handle rotation distances greater than string length. Both left and right rotations follow the same pattern: split the string and concatenate in reverse order.

Updated on: 2026-03-24T21:03:20+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements