![]() |
VOOZH | about |
In string manipulation tasks, especially in algorithmic challenges or encoding/decoding scenarios, we sometimes need to rotate (or shift) characters in a string either to the left or right by a certain number of positions.
For example, let's take a string s = "geeks" and we need to perform a left and right shift of k=2 places:
s = "geeks"
left shift = "eeksge"
right shift = "ksgee"
This article explores different ways to perform such shifts in Python using different methods, let's explore them with examples:
This method combines slicing with string multiplication to handle shifts efficiently in a single step. It works by dividing the string at the specified index and rearranging the parts.
Left Shift: ksforgeeksgee Right Shift: eksgeeksforge
Explanation:
Modulo operator (%) ensures the shift value remains within the bounds of the string length. This avoids unnecessary operations when the shift value exceeds the string length.
Left Shift: sforgeeksgeek Right Shift: eeksgeeksforg
Explanation:
Deque (double-ended queue) from the collections module is designed for efficient rotations and manipulations. This method uses the built-in rotate function of deque for shifting characters.
Left Shift: ksforgeeksgee Right Shift: eksgeeksforge
Explanation:
This approach uses list comprehension to calculate the shifted indices and reconstructs the string using the join() function. It provides a flexible way to perform shifts..
Left Shift: ksforgeeksgee Right Shift: eksgeeksforge
Explanation:
Cycle creates an infinitely repeating iterable from the original string. This allows us to extract the desired shifted sequence using slicing.
Left Shift: ksforgeeksgee Right Shift: eksgeeksforge
Explanation:
Also read: String slicing, collections.deque, list comprehension, itertools.cycle, islice.