Open In App

String slicing in Python to Rotate a String

Last Updated : 30 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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"

Rotate string for string slicing

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




# 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)


Output:

Left Rotation  : eksforGeeksGe 
Right Rotation : ksGeeksforGee

Using extending the string

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




# Function to rotate string left and right by d length
 
def rotate(str1,n):
 
    # Create the extended string and index of for rotation
    temp = str1 + str1
    l1 = len(str1)
    l2 = len(temp)
    Lfirst = temp[n  : l1+n]
    Lfirst = temp[l1-n : l2-n]
 
    # now printing the string
    print ("Left Rotation : ", Lfirst)
    print ("Right Rotation : ", Lfirst )
 
# Driver program
if __name__ == "__main__":
    input = 'GeeksforGeeks'
    d=2
    rotate(input,d)


Output

Left Rotation :  ksGeeksforGee
Right Rotation :  ksGeeksforGee

String slicing in Python to Rotate a String Using deque

Take the input string s and the number of rotations d. Create a deque from the string s. Rotate the deque by d positions to the left or right using the rotate() method. Convert the deque back to a string using join() method and return the rotated string.

Algorithm

1. Take the input string s and the number of rotations d.
2. Create a deque from the string s.
3. If d is positive, rotate the deque to the left by d positions using the rotate() method.
  If d is negative, rotate the deque to the right by -d positions using the rotate() method.
4. Convert the deque back to a string using join() method and return the rotated string.
 

Python3




from collections import deque
 
def rotate_string(s, d):
    deq = deque(s)
    if d > 0:
        deq.rotate(-d)
    else:
        deq.rotate(abs(d))
    return ''.join(deq)
 
s = 'GeeksforGeeks'
d = 2
 
left_rotated = rotate_string(s, d)
right_rotated = rotate_string(s, -d)
 
print("Left Rotation: ", left_rotated)
print("Right Rotation: ", right_rotated)


Output

Left Rotation:  eksforGeeksGe
Right Rotation:  ksGeeksforGee

Time complexity: O(n), where n is the length of the string s.
Auxiliary Space: O(n), where n is the length of the string s.



Similar Reads

Program to cyclically rotate an array by one in Python | List Slicing
Given an array, cyclically rotate the array clockwise by one. In this article, we will see how to cyclically rotate an array by one in Python. Example Input: arr = [1, 2, 3, 4, 5]Output: arr = [5, 1, 2, 3, 4]Reference: Program to cyclically rotate an array by one Python Program to Cyclically Rotate an Array by One in PythonBelow are the methods or
2 min read
Rotate a picture using ndimage.rotate Scipy
Prerequisites: Mathplotlib, Scipy Some of the most common tasks in image processing are displaying images, Basic manipulations, Image filtering, Image segmentation. In this article, we will use a SciPy module "ndimage.rotate()" to rotate. The SciPy ndimage submodule is dedicated to image processing. Here, ndimage means an n-dimensional image. Appro
2 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
Python | Get the substring from given string using list slicing
Given a string, write a Python program to get the substring from given string using list slicing. Let’s try to get this using different examples. What is substring? A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the index of a substring and more. Syntax of list slicin
4 min read
Python | Reverse Slicing of given string
Sometimes, while working with strings we might have a problem in which we need to perform the reverse slicing of string, i.e slicing the string for certain characters from the rear end. Let's discuss certain ways in which this can be done. Method #1 : Using join() + reversed() The combination of above function can be used to perform this particular
5 min read
String Slicing in Python
Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to end. How String slicing in Python works For understanding slicing we will use different methods, here we will cover 2 methods of string slicing, one using the in-build slice() method and another using the [:] array slice. String slicing in
4 min read
Python | Reverse Interval Slicing String
Sometimes, while working with strings, we can have a problem in which we need to perform string slicing. In this, we can have a variant in which we need to perform reverse slicing that too interval. This kind of application can come in day-day programming. Let us discuss certain ways in which this task can be performed. Method #1: Using String Slic
4 min read
Python | Reverse Incremental String Slicing
Sometimes, while working with Python strings, we can have a problem in which we need to perform the slice and print of strings in reverse order. This can have applications in day-day programming. Let us discuss certain ways in which this task can be performed. Method #1: Using loops This is the brute-force way in which this task can be performed. I
4 min read
Interesting facts about strings in Python | Set 2 (Slicing)
Creating a String Strings in Python can be created using single quotes or double quotes or even triple quotes. # Python Program for # Creation of String # Creating a String # with single Quotes String1 = 'Welcome to the Geeks World' print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'
4 min read
Python Slicing | Reverse an array in groups of given size
Given an array, reverse every sub-array formed by consecutive k elements. Examples: Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] k = 3 Output: [3, 2, 1, 6, 5, 4, 9, 8, 7] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k = 5 Output: [5, 4, 3, 2, 1, 8, 7, 6] Input: arr = [1, 2, 3, 4, 5, 6] k = 1 Output: [1, 2, 3, 4, 5, 6] Input: arr = [1, 2, 3, 4, 5, 6, 7, 8] k =
5 min read