The Wayback Machine - https://web.archive.org/web/20240909203640/https://www.geeksforgeeks.org/string-slicing-python-rotate-string/
Open In App

String slicing in Python to Rotate a String

Last Updated : 30 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Medium
23.46%
12.4K

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
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 worksFor 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
5 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
Python Slicing | Extract ‘k’ bits from a given position
How to extract ‘k’ bits from a given position ‘p’ in a number? Examples: Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 10101011 in binary, so, you should get only 10101 i.e. 21. Input : number = 72 k = 5 p = 1 Output : The extracted number is 8 72 is represented as 1001000 in binary, so, you should get o
4 min read
Python | Custom slicing in List
Sometimes, while working with Python, we can come to a problem in which we need to perform the list slicing. There can be many variants of list slicing. One can have custom slice interval and slicing elements. Let's discuss problem to such problem. Method : Using compress() + cycle() The combination of above functions can be used to perform this pa
2 min read
Python List Comprehension and Slicing
List comprehension is an elegant way to define and create a list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence
5 min read
Slicing with Negative Numbers in Python
Slicing is an essential concept in Python, it allows programmers to access parts of sequences such as strings, lists, and tuples. In this article, we will learn how to perform slicing with negative indexing in Python. Indexing in PythonIn the world of programming, indexing starts at 0, and Python also follows 0-indexing what makes Python different
6 min read
Python List Slicing
In Python, list slicing is a common practice and it is the most used technique for programmers to solve efficient problems. Consider a Python list, in order to access a range of elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:). With this operator, one can specify where to start the
6 min read
Python slicing multi-dimensional arrays
Python's NumPy package makes slicing multi-dimensional arrays a valuable tool for data manipulation and analysis. It enables efficient subset data extraction and manipulation from arrays, making it a useful skill for any programmer, engineer, or data scientist. Python Slicing Multi-Dimensional ArraysSlicing is a method for taking out an array secti
4 min read
Implementing slicing in __getitem__
The __getitem__ method is used for accessing list items, array elements, dictionary entries etc. slice is a constructor in Python that creates slice object to represent set of indices that the range(start, stop, step) specifies. __getitem__ method can be implement in a class, and the behavior of slicing can be defined inside it. Syntax: __getitem__
2 min read
Data Slicing using PyQtGraph
In this article, we will see how we can perform data slicing using PyQtGraph module in Python. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and sec
5 min read
Basic Slicing and Advanced Indexing in NumPy
Indexing a NumPy array means accessing the elements of the NumPy array at the given index. There are two types of indexing in NumPy: basic indexing and advanced indexing. Slicing a NumPy array means accessing the subset of the array. It means extracting a range of elements from the data. In this tutorial, we will cover basic slicing and advanced in
5 min read
Python | Ways to rotate a list
The rotation of a list has been discussed earlier also, but this particular article focuses on shorthands and various short techniques to achieve this in one-liners or one word. This operation is quite essential in a programmer's life to achieve various tasks. Let's discuss different ways we can rotate a list in Python. Method 1: Rotate a list usin
8 min read
Python PIL | paste() and rotate() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. PIL.Image.Image.paste() method is used to paste an image on another image. This is where the new() method comes in handy. Syntax: PIL.Image.Image.paste(image_1, image_2, box=None, mask=None) OR image_object.paste(image_2, box=None, mask=None)Par
2 min read
SymPy | Polyhedron.rotate() in Python
Polyhedron.rotate() : rotate() is a sympy Python library function that rotation about an axis of the polyhedra. Syntax : sympy.combinatorics.Polyhedrons.Polyhedron.rotate() Return : rotation about an axis of the polyhedra Code #1 : rotate() Example - tetrahedron # Python code explaining # SymPy.Polyhedron.rotate() # importing SymPy libraries from s
1 min read
Python | Decimal rotate() method
Decimal#rotate() : rotate() is a Decimal class method which returns the rotated copy of x, y times Syntax: Decimal.rotate() Parameter: Decimal values Return: the rotated copy of x, y times Code #1 : Example for rotate() method # Python Program explaining # rotate() method # loading decimal library from decimal import * # Initializing a decimal valu
2 min read
Python | Sympy Ellipse.rotate() method
In Sympy, the function rotate() is used to rotate the ellipse counterclockwise about the given point by the given angle. Syntax: Ellipse.rotate(angle=0, pt=None) Parameters: angle: in radian pt: point about which ellipse is rotated in counterclockwise. Returns: rotated ellipse Example #1: # import sympy and pi, Ellipse from sympy import Ellipse, pi
1 min read
Wand rotate() function in Python
Rotation changes the orientation of image or it rotates image to a particular angle. rotate() takes a degree which can be 0 to 359. (Actually you can pass 360, 361, or more but it will be the same to 0, 1, or more respectively.). Syntax : wand.image.rotate(degree, background, reset_coords) Parameters : ParameterInput TypeDescriptiondegreenumbers.Re
1 min read
Wand rotate() function - Python
The rotate() function is an inbuilt function in the Python Wand ImageMagick library which is used to rotates the image right. It takes a background color for which rotation is not available. Syntax: rotate(degree, background, reset_coords) Parameters: This function accepts three parameters as mentioned above and defined below: degree: This paramete
2 min read
Python OpenCV - cv2.rotate() method
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.rotate() method is used to rotate a 2D array in multiples of 90 degrees. The function cv::rotate rotates the array in three different ways. Syntax: cv2.cv.rotate( src, rotateCode[, dst] )Parameters: src: It is the image whose color space is to be changed.r
2 min read
Rotate image without cutting off sides using Python - OpenCV
Prerequisite: Image Processing in Python (Scaling, Rotating, Shifting and Edge Detection) Rotating images with OpenCV is easy, but sometimes simple rotation tasks cropped/cut sides of an image, which leads to a half image. Now, In this tutorial, We will explore a solution to safely rotate an image without cropping/cutting sides of an image so that
6 min read
How to rotate an image using Python?
In this article, let's see how to rotate an Image using Python. By Image Rotation, the image is rotated about its center by a specified number of degrees. The rotation of an image is a geometric transformation. It can be done either by Forward Transformation (or) Inverse Transformation. Here Image Processing Library with Pillow uses Inverse Transfo
2 min read
Rotate-matrix module in Python
The rotate-matrix is an interesting new python module, which allows conversion of a matrix(2-D array) into either clockwise rotation or anti-clockwise rotation. It at present consists of only two methods. You can loop through these methods for 'n' number of rotations. Installation This module doesn't come in-built with python but can be installed u
1 min read
Python Pillow - Flip and Rotate Images
Prerequisites: Pillow Python Pillow or PIL is the Python library that provides image editing and manipulating features. The Image Module in it provides a number of functions to flip and rotate images. image.transpose() is the function used to rotate and flip images with necessary keywords as parameters. Syntax: image.transpose(appropriate keyword)
2 min read
How to rotate an image by an angle using PyTorch in Python?
In this article, we are going to see how to rotate an image by an angle in PyTorch. To achieve this, we can use RandomRotation() method. RandomRotation() transform accepts both PIL and tensor images. A Tensor Image is a tensor with (C, H, W) shape, C is for the number of channels, H and W are for the height and width of the image respectively. Synt
2 min read
How to rotate text in Matplotlib – Python
In this article, we will learn how to rotate text in Matplotlib in Python. Out of the many parameters in matplotlib.text(), there are three main parameters that will define text rotation and how the text will be rotated. Syntax of matplotlib.text method Syntax: matplotlib.text(x=0, y=0, text='', rotation=None, rotation_mode=None, transform_rotates_
2 min read
Decimal Functions in Python | Set 2 (logical_and(), normalize(), quantize(), rotate() ... )
Some of the Decimal functions have been discussed in Set 1 below Decimal Functions in Python | Set 1 More functions are discussed in this article.1. logical_and() :- This function computes digit-wise logical "and" operation of the number. Digits can only have the values 0 or 1. 2. logical_or() :- This function computes digit-wise logical "or" opera
6 min read