String Rotation using String Slicing in Python
In this tutorial, we are going to solve a task of rotating a string using the method of String slicing in Python. For doing this problem, first we need to know about a string in Python.
A string in Python is nothing but an array of characters enclosed within single or double quotes. Python supports in-built functions on strings which let us manipulate and modify them the way we want.
One such function is String Slicing.
Now, before diving deep, let’s proceed with the idea of String Slicing first !!!
What is String Slicing?
String Slicing in Python extracts individual characters or substrings,i.e a slice of characters. By doing this, we can use the range of characters we actually need from a given string. The syntax for string slicing is as follows :
string_name[start_index: end_index: steps]
- start_index : the index starting from which the slicing will take place;inclusive
- end_index : the index where the slicing ends;not inclusive
- steps : distance between two characters
Here’s two examples of String Slicing :
# python code to show string slicing x = "India is my nation" # printing substring starting from 2nd index to 13th index with a gap of 2 characters print(x[2:13:2]) #printing substring from 12th index to the last print(x[12:])
Output dai yn nation
How to Implement this Concept in the Given Task?
In this task, we would be doing left(anticlockwise) rotation and right(clockwise) rotation of the given string st of size n by e elements where e<=n. Here we have taken e as 3 by default, if you wish you can take any other value instead.
The approach is as follows :
- First, divide the given string into two portions into first and second for both left and right rotation.
- For left rotation, left first = st[0:e] and left second= st[e:] .
- For right rotation, right first = st[0 : len(st)-e] and right second = st[len(st)-e :].
- Next, add first and second respectively.
- For left rotation, the first e elements are sliced and moved to the end of the string;hence we get an anticlockwise rotated string by e elements as output.
- For right rotation, we see the reverse; the last e elements are sliced and moved to the starting of the string;hence we get a clockwise rotated string by e elements as output.
# rot function for rotating the strings def rot(st,e): # string slicing into left first and second strings and right first and second strings lf = st[0 : e] ls = st[e :] rf = st[0 : len(st)-e] rs = st[len(st)-e : ] # concatenation of the second and first strings print("Left Rotation : ", (ls + lf) ) print("Right Rotation : ", (rs + rf) ) # main code if __name__ == "__main__": st = input('Enter the string: ') e=3 rot(st,e)
Output :
Enter the string: Codespeedy Left Rotation : espeedyCod Right Rotation : edyCodespe
Leave a Reply