Open In App

Python – Right and Left Shift characters in String

Last Updated : 08 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python Strings, we can have problem in which we have both right and left rotate count of characters in String and would like to know the resultant condition of String. This type of problem occurs in competitive programming. Lets discuss certain ways in which this task can be performed. 

Method #1 : Using String multiplication + string slicing 

The combination of above functions can be used to perform this task. In this, we multiply the string thrice, perform the concatenation and selectively slice string to get required result. 

Python3




# Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using String multiplication + string slicing
 
# Initializing string
test_str = 'geeksforgeeks'
 
# Printing original string
print("The original string is : " + test_str)
 
# Initializing right rot
r_rot = 7
 
# Initializing left rot
l_rot = 3
 
# Right and Left Shift characters in String
# Using String multiplication + string slicing
res = (test_str * 3)[len(test_str) + r_rot - l_rot:
                     2 * len(test_str) + r_rot - l_rot]
 
# Printing result
print("The string after rotation is : " + str(res))


Output : 

The original string is : geeksforgeeks
The string after rotation is : sforgeeksgeek

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #2: Using % operator and string slicing

The combination of the above functionalities can also be used to perform this task. In this, we find the mod of rotation difference with length to compute the string position.

Python3




# Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using % operator and string slicing
 
# Initializing string
test_str = 'geeksforgeeks'
 
# Printing original string
print("The original string is : " + test_str)
 
# Initializing right rot
r_rot = 7
 
# Initializing left rot
l_rot = 3
 
# Right and Left Shift characters in String
# Using % operator and string slicing
temp = (r_rot - l_rot) % len(test_str)
res = test_str[temp:] + test_str[: temp]
 
# Printing result
print("The string after rotation is : " + str(res))


Output : 

The original string is : geeksforgeeks
The string after rotation is : sforgeeksgeek

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3: Using list slicing and join

this approach uses list slicing and join to rotate the string. It converts the input string to a list of characters, slices the list into two parts, concatenates them to get the rotated list, and then joins the list back into a string to get the rotated string.

Algorithm:

  1. Convert the input string into a list of characters.
  2. Slice the list into two parts, one from the starting index to the number of characters to be shifted and the other from the number of characters to be shifted to the end of the list.
  3. Concatenate the second part with the first part to get the rotated list.
  4. Join the list into a string to get the rotated string.
  5. Print the rotated string.

Python3




def left_shift_string(string, n):
    char_list = list(string)
    rotated_list = char_list[n:] + char_list[:n]
    rotated_string = "".join(rotated_list)
    return rotated_string
 
def right_shift_string(string, n):
    char_list = list(string)
    rotated_list = char_list[-n:] + char_list[:-n]
    rotated_string = "".join(rotated_list)
    return rotated_string
 
string = "geeksforgeeks"
n = 3
 
left_rotated_string = left_shift_string(string, n)
right_rotated_string = right_shift_string(string, n)
 
print("Original string:", string)
print("Left rotated string:", left_rotated_string)
print("Right rotated string:", right_rotated_string)


Output

Original string: geeksforgeeks
Left rotated string: ksforgeeksgee
Right rotated string: eksgeeksforge

Time complexity: O(n), where n is the length of the string.
Auxiliary Space: O(n), as we are creating a list of characters to store the rotated list.

Approach 4: Using lambda function

  1. We define a lambda function called rotate that performs the string rotation operation.
  2. The lambda function takes a string s as its input and returns the rotated string.
  3. We then use the lambda function rotate to perform the string rotation operation on the input string test_str. Finally, we print the rotated string res.

Below is the code for the above approach is as follows: 

Python3




# Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using String multiplication + string slicing
 
# Initializing string
test_str = 'geeksforgeeks'
 
# Printing original string
print("The original string is : " + test_str)
 
# Initializing right rot
r_rot = 7
 
# Initializing left rot
l_rot = 3
 
# Rotating string
# using lambda function 
rotate = lambda s: (s * 3)[len(s) + r_rot - l_rot : 2 * len(s) + r_rot - l_rot]
 
# Right and Left Shift characters in String
# Using String multiplication + string slicing
res = rotate(test_str)
 
# Printing result
print("The string after rotation is : " + str(res))


Output

The original string is : geeksforgeeks
The string after rotation is : sforgeeksgeek

Time Complexity: O(n), where n is the length of the input string test_str
Auxiliary Space: O(n), as we are creating a new string with length 3n using string multiplication.

Approach #5: Using List comprehension and string concatenation

We can use a list comprehension to shift the characters in the string and then concatenate the resulting characters to form the rotated string.

Steps:

  1. Initialize an empty list to store the shifted characters.
  2. Use a list comprehension to shift the characters to the right or left based on the rotation value.
  3. Concatenate the shifted characters to form the rotated string.
  4. Return the rotated string.

Python3




# Python3 code to demonstrate working of
# Right and Left Shift characters in String
# Using list comprehension and string concatenation
 
# Initializing string
test_str = 'geeksforgeeks'
 
# Printing original string
print("The original string is : " + test_str)
 
# Initializing right rot
r_rot = 7
 
# Initializing left rot
l_rot = 3
 
# Using list comprehension and string concatenation
res = ''.join([test_str[(i + r_rot - l_rot) % len(test_str)]
               for i in range(len(test_str))])
 
# Printing result
print("The string after rotation is : " + res)


Output

The original string is : geeksforgeeks
The string after rotation is : sforgeeksgeek

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



Similar Reads

Python3 Program to Minimize characters to be changed to make the left and right rotation of a string same
Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc”Changing the character at position 3 to 'a' and c
3 min read
NumPy ndarray.__ilshift__() | Shift NumPy Array Elements to Left
The ndarray.__ilshift__() method is an in-place left-shift operation. It shifts elements in the array to the left of the number of positions specified. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__ilshift__() method print(gfg.__ilshift__(2)) Output[ 4 8 12 16 20] SyntaxSyntax: ndarray.__ilshift__($self,
1 min read
NumPy ndarray.__irshift__() | Shift NumPy Array Elements to Right
The ndarray.__irshift__() method returns a new array where each element is right-shifted by the value that is passed as a parameter. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__irshift__() method print(gfg.__irshift__(2)) Output[0 0 0 1 1] SyntaxSyntax: ndarray.__irshift__($self, value, /) Parameter se
1 min read
Python - Reverse Shift characters by K
Given a String, reverse shift each character according to its alphabetic position by K, including cyclic shift. Input : test_str = 'bccd', K = 1 Output : abbc Explanation : 1 alphabet before b is 'a' and so on. Input : test_str = 'bccd', K = 2 Output : zaab Explanation : 2 alphabets before b is 'z' (rounded) and so on. Method : Using maketrans() +
3 min read
Python3 Program for Left Rotation and Right Rotation of a String
Given a string of size n, write functions to perform the following operations on a 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 :
3 min read
Python Program to check if elements to the left and right of the pivot are smaller or greater respectively
Given a list and an index, the task is to write a Python program to first select the element at that index as the pivot element and then test if elements are greater to its right and smaller to its left or not. Examples: Input : test_list = [4, 3, 5, 6, 9, 16, 11, 10, 12], K = 4 Output : True Explanation : Elements at Kth index is 9, elements befor
3 min read
Python Pandas - Check if the interval is open on the left and right side
In pandas Interval.closed_left and Interval.closed_right attributes are used to check if the interval is open on left and right side. Intervals: Closed interval : closed ='both' represents closed interval. The closed interval contains its endpoints. it is of the form [a,b] and it has the condition a<=x<=b.Open interval: closed =' neither' rep
2 min read
Right and Left Hand Detection Using Python
In this article, we are going to see how to Detect Hands using Python. We will use mediapipe and OpenCV libraries in python to detect the Right Hand and Left Hand. We will be using the Hands model from mediapipe solutions to detect hands, it is a palm detection model that operates on the full image and returns an oriented hand bounding box. Require
5 min read
Use different y-axes on the left and right of a Matplotlib plot
In this article, we are going to discuss how to create y-axes of both sides of a Matplotlib plot. Sometimes for quick data analysis, it is required to create a single graph having two data variables with different scales. For this purpose twin axes methods are used i.e. dual X or Y-axes. The matplotlib.axes.Axes.twinx() function in axes module of m
2 min read
Python3 Program for Longest subsequence of a number having same left and right rotation
Given a numeric string S, the task is to find the maximum length of a subsequence having its left rotation equal to its right rotation. Examples: Input: S = "100210601" Output: 4 Explanation: The subsequence "0000" satisfies the necessary condition. The subsequence "1010" generates the string "0101" on left rotation and string "0101" on right rotat
4 min read
Practice Tags :