Rotate and Reverse a String
In this section, we will demonstrate how to take a specified number of characters from the head or tail of a given string, rotate them, and concatenate the results in reverse order.
Example
def rotate(input, d): # Head slicing and rotation Lfirst = input[0 : d] Lsecond = input[d :] # Tail slicing and rotation Rfirst = input[0 : len(input)-d] Rsecond = input[len(input)-d : ] # Printing results print("Head slice rotated: ", (Lsecond + Lfirst)) print("Tail slice rotated: ", (Rsecond + Rfirst)) if __name__ == "__main__": input = 'Runoob' d = 2 # Slice and rotate 2 characters rotate(input, d)
Output:
Head slice rotated: noobRu Tail slice rotated: obRuno
In this example:
We take the first two characters from the head or tail and rotate the string by concatenating the remaining part with the sliced section.
The first operation rotates the head, and the second operation rotates the tail of the string.