String slicing in Python to Rotate a String
Last Updated :
05 Mar, 2025
Improve
Given a string of size n, write functions to perform following operations on string:
- Left (Or anticlockwise) rotate the given string by d elements (where d <= n).
- Right (Or clockwise) rotate the given string by d elements (where d <= n).
For example, let’s take a string s = “GeeksforGeeks” and d = 2, so for this example, our Left Rotation will be “eksforGeeksGe” and Right Rotation will be “ksGeeksforGee”. Let’s discuss some of the ways to do it with examples.
Using Slicing
Python’s string slicing provides a quick way to rotate strings. The idea is to divide the string into two parts and rearrange them to get the desired rotation.
s = "GeeksforGeeks"
d = 2
# Left Rotation
left = s[d:] + s[:d]
# Right Rotation
right = s[-d:] + s[:-d]
print("Left Rotation:", left)
print("Right Rotation:", right)
Output
Left Rotation: eksforGeeksGe Right Rotation: ksGeeksforGee
Explanation:
- Left Rotation: Split into s[:d] (first part) and s[d:] (second part), then concatenate in reverse order.
- Right Rotation: Split into s[:-d] (first part) and s[-d:] (second part), then concatenate.
By Extending the String
Create an extended string by concatenating ‘s + s’ as it will cointain all possible rotations and then extract the rotated substring by slicing within the extended string.
s = "GeeksforGeeks"
d = 2
# Create extended string
ext_s = s + s
n = len(s)
# Left Rotation
left = ext_s[d:n + d]
# Right Rotation
right = ext_s[n - d: 2 * n - d]
print("Left Rotation:", left)
print("Right Rotation:", right)
Output
Left Rotation: eksforGeeksGe Right Rotation: ksGeeksforGee
Explanation:
- extracting a substring from index ‘d to d+n’ using ext_s[d:n + d] (n = length of string) will get us the ‘Left Rotation’.
- similarly, extracting a substring from index ‘n-d to 2n-d’ using ext_s[n – d: 2 * n – d] (n = length of string) will get us the ‘Right Rotation’.