How to rotate a string in python using string slicing
Strings are a vastly used data type to store all kinds of text data: characters, alphabets, numbers, and alphanumeric. They are immutable; therefore, we can not alter their's contents; however, we can manipulate them to achieve the desired results. Python offers various operations to manipulate strings, including concatenation, formatting, and slicing.
What is string rotation?
String rotation refers to moving the characters of a string forward or backward, making it change its index position. While rotating, we shift the position of the characters circularly. For example, if the last index character is shifted one position forward, it will occupy the first index.
There are two types of string rotation: left and right.
Left Rotation: In this case, characters from the beginning are shifted to the left and appended to the end of the string.
Right Rotation: In this case, characters from the end are shifted to the right and prepended to the beginning of the string.
Simple string slicing
In this method, we take a string and the number of rotations we want to perform. The string is then sliced into portions by passing the starting and ending indexes. The slices are then concatenated to achieve the new rotated string.
Enter a number as input below to run the code.
def rotateStr(string , num):#slice string in start and end for leftleftStart = string[ num :]leftEnd = string[ 0 : num ]#slice string in start and end for rightrightStart = string[ len(string)- num :]rightEnd = string[ 0 : len(string)- num]#concatenate and print the string respectivelyprint 'Left Rotation : ', (leftStart + leftEnd)print 'Right Rotation : ',(rightStart + rightEnd)#Enter a number as input belownum = input()string = 'Educative'print('Original String : ' + string)print('\nNumber of Rotations : {}'.format(num))print('\nRotation is called....\n')rotateStr(string , num)
Enter the input below
Code explanation
Line 1: The
rotateStr()function is defined that takesstringandnumas parameters and prints the results.Line 4:
leftStartis assigned characters from the indexnumtill the end of the string.Line 5:
leftEndis assigned characters from the index0till indexnumof the string.Line 8:
rightStartis assigned characters from the indexlen(string) - numtill the end of the string.Line 9:
rightEndis assigned characters from the index0till indexlen(string) - numof the string.Lines 12–13: The left and right strings are concatenated and printed respectfully.
Lines 16: The
input()function is used to take input for the number of rotationsnumto be performed on thestring.Line 17: The
stringis assigned text data that will be rotated.Line 23: The
rotateStr()function is called to perform the rotation operation on the givenstring.
String slicing using deque
In this method, we import the deque class from the collections module that contains a rotate() method that is directly used to perform rotation. Note that implicit string slicing occurs when the rotate() method is called.
Enter a number as input below to run the code.
#import deque classfrom collections import dequedef rotateStr(string, num):deqStr = deque(string)deqStr.rotate(num)return ''.join(deqStr)num = input()string = 'Educative'print('Original String : ' + string)print('\nNumber of Rotations : {}'.format(num))print('\nRotation is called....\n')#call left and right rotations respectivelyrotateLeft = rotateStr(string , -num)rotateRight = rotateStr(string , num)#print the rotated stringsprint'Left Rotation: ', rotateLeftprint'Right Rotation: ', rotateRight
Enter the input below
Code explanation
Line 2: The
dequeclass is imported fromcollectionsclass to use its rotate method.Line 5: The
rotateStr()function is defined that takesstringandnumas parameters and prints the results.Line 6: The
deqStrobject is created for thedequeclass and is initialized with thestringcharacters.Line 7: The
rotate()method is called from thedequeclass that rotates thestringto the left ifnumis negative and to the right ifnumis positive.Line 8:
join()is used to join all the characters of thestringtogether which is then returned as a result.Line 11: The
input()function is used to take input for the number of rotationsnumto be performed on thestring.Line 12: The
stringis assigned text data that will be rotated.Line 19:
rotateLeftis assigned the result received whenrotateStr()function is called with a negativenumparameter.Line 20:
rotateRightis assigned the result received whenrotateStr()function is called with a positivenumparameter.Lines 23–24: The
rotateLeftandrotateRightstrings are printed respectfully.
Summary
Both methods slightly differ in functionality; however, both apply the string slicing operation to achieve the desired outputs. It is important to note that the time and space complexity for both methods is O(n); hence we can use any of them to rotate a string.
Test your understanding
string = 'hello'
rotationCount = 3
What will be the left rotation for this string?
llohe
lohel
llohe
Free Resources