String slicing in Python to rotate a string
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).
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"
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,
- 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 : ].
- Now concatenate these two parts second + first accordingly.
# Function to rotate string left and right by d length def rotate(input,d): # slice string in two parts for left and right Lfirst = input[0 : d] Lsecond = input[d :] Rfirst = input[0 : len(input)-d] Rsecond = input[len(input)-d : ] # now concatenate two parts together print "Left Rotation : ", (Lsecond + Lfirst) print "Right Rotation : ", (Rsecond + Rfirst) # Driver program if __name__ == "__main__": input = 'GeeksforGeeks' d=2 rotate(input,d) |
chevron_right
filter_none
Output:
Left Rotation : eksforGeeksGe Right Rotation : ksGeeksforGee
Recommended Posts:
- String slicing in Python to check if a string can become empty by recursive deletion
- Python | Reverse Slicing of given string
- Python | Get the substring from given string using list slicing
- Program to cyclically rotate an array by one in Python | List Slicing
- Python | Check if given string can be formed by concatenating string elements of list
- Python | Merge Tuple String List values to String
- Python | Sorting string using order defined by another string
- Python | Check if string ends with any string in given list
- Python | Check if a given string is binary string or not
- Python | Sort each String in String list
- Python List Comprehension and Slicing
- Python | Custom slicing in List
- Python | Variable list slicing
- Python | Alternate range slicing in list
- Python Slicing | Extract ‘k’ bits from a given position
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

