String rotation using python

In this article we shall see how to perform string rotation using python. With the help of the slicing operation this can be achieved in a single line in python.

What is string rotation?

String rotation is the concept of shifting the characters in a string either right side or left side to the current position.

How does it work in python?

In python it is pretty simple with the slicing operator. Follow these steps to perform the string rotation using python.

  1. Get/input the number of rotations required.
  2. With the help of the slicing operator get the characters starting from the index equal to the rotations required.
  3. Again with the help of the slicing operator get the characters whose index does not exceed the rotation value.
  4. Combine both strings to get the desired string.

Consider the following string Elephant. I want to rotate/shift this string to 3 places. I can do something like this following the steps above to get the desired result.

string = 'Elephant'
print(string[3:] + string[:3])

The output of the above code is,


As you can see the first three letters are rotated to the left as we have given 3 as the rotation value.


Hope this article is helpful. Happy coding !