Signup/Sign In

String slicing in Python to rotate a string

In this tutorial, you will learn to rotate a string in Python using slicing. Strings in Python are a sequence of characters. Slicing is the process of accessing a part or a subset of a given string. For a given string of size n, we have to rotate the string by d elements. Where d is smaller than or equal to the size of the string. A string can be rotated clockwise (right rotation) or anticlockwise (left rotation). We will perform both rotations and give output for both rotations in our program.

Look at the examples to understand the input and output format.

Input:

s="studytonight"

d=3

Output:

Left Rotation : dytonightstu
Right Rotation : ghtstudytoni

To solve this, we will be using the concept of slicing in Python. Slicing will be used to divide the string into two parts.

  1. For Left rotation, we will store the characters from the index 0 to d in the first part and the remaining characters in the second part.
  2. For Right rotation, we will store the characters from the index 0 to (n-d) where n is the size of the string and the remaining characters in the second part.
  3. Now we will join the second and first part as second + first for both rotations.

Algorithm

Look at the algorithm to understand the approach better.

Step 1- Define a function that will rotate the string

Step 2- In the function, declare variables for the first and second part of the string for both left and right rotation

Step 3- Use slicing to get the characters in the first and the second part as discussed above

Step 4- Print the rotated strings by joining the second and the first part

Step 5- Declare string and value of d

Step 6- Pass the string and d in the function

Python Program

In this program, we have used len() method of the String class to get the length of the string. To join or concatenate the first and the second part of the string after slicing, we have used the concatenation (+) operator.

# Function to rotate string left and right by d

def rotate_string(s,d): 
  
    # slice string in two parts for left and right 
    Lfirst = s[0 : d] 
    Lsecond = s[d :] 
    Rfirst = s[0 : len(s)-d] 
    Rsecond = s[len(s)-d : ] 
  
    # now join two parts together 
    print ("Left Rotation : ", (Lsecond + Lfirst) )
    print ("Right Rotation : ", (Rsecond + Rfirst)) 
  
string = 'Studytonight'
d=4
rotate_string(string,d) 


Left Rotation : ytonightStud
Right Rotation : ightStudyton

Conclusion

In this tutorial, we have learned to write a program for rotating a string by d elements. We have performed both left and right rotation on a string using the slicing concept.