String Slicing in Python to Rotate a String (original) (raw)

Last Updated : 12 Jan, 2026

Given a string of length n, rotate the string either, Left (anticlockwise) by d positions or Right (clockwise) by d positions where 0 ≤ d ≤ n. For Example:

**Input: "GeeksforGeeks", d=2
**Output: Left Rotation: "eksforGeeksGe"
Right Rotation: "ksGeeksforGee"

Let's discuss different ways to rotate a string in Python.

Using String Slicing

This method rotates a string by cutting it at a given position and then joining the two parts in reverse order to form the rotated result.

Python `

s = "GeeksforGeeks" d = 2

left = s[d:] + s[:d] right = s[-d:] + s[:-d]

print("Left rotation:", left) print("Right rotation:", right)

`

Output

Left rotation: eksforGeeksGe Right rotation: ksGeeksforGee

**Explanation:

By Extending the String

This method doubles the string (s + s) so all possible rotations appear inside it. Then the rotated version is obtained by slicing the extended string at the correct position.

Python `

s = "GeeksforGeeks" d = 2

ext = s + s n = len(s)

left = ext[d : d + n] right = ext[n - d : 2*n - d]

print("Left Rotation:", left) print("Right Rotation:", right)

`

Output

Left Rotation: eksforGeeksGe Right Rotation: ksGeeksforGee

**Explanation:

Rotation Using Collections.deque

This method converts the string into a deque (double-ended queue) so that characters can be rotated directly using the built-in rotate() function, avoiding manual slicing and making rotation efficient.

Python `

from collections import deque s = "GeeksforGeeks" d = 2

dq = deque(s)

Left Rotation

dq.rotate(-d) left = ''.join(dq)

Right Rotation

dq.rotate(d) # undo then rotate right dq.rotate(d)
right = ''.join(dq)

print("Left Rotation:", left) print("Right Rotation:", right)

`

Output

Left Rotation: eksforGeeksGe Right Rotation: ksGeeksforGee

**Explanation:

Using For Loop

This approach rotates the string by rearranging its characters step by step using loops, so the shifting process can be seen clearly instead of happening automatically through slicing or built-in functions.

Python `

s = "GeeksforGeeks" d = 2 n = len(s)

Left Rotation

left = "" for i in range(d, n): left += s[i] for i in range(d): left += s[i]

Right Rotation

right = "" for i in range(n - d, n): right += s[i] for i in range(n - d): right += s[i]

print("Left Rotation:", left) print("Right Rotation:", right)

`

Output

Left Rotation: eksforGeeksGe Right Rotation: ksGeeksforGee

**Explanation: