String slicing in Python to Rotate a String

String slicing in Python to Rotate a String

String slicing in Python can be used to easily rotate a string either to the left or to the right.

1. Left Rotation:

To perform a left rotation by n characters, you can slice the string from the nth index and append the first n characters to the end.

def left_rotate(s, n): return s[n:] + s[:n] # Example: s = "abcdef" rotated_string = left_rotate(s, 2) print(rotated_string) # Output: "cdefab" 

2. Right Rotation:

To perform a right rotation by n characters, you can slice the last n characters and prepend them to the beginning.

def right_rotate(s, n): return s[-n:] + s[:-n] # Example: s = "abcdef" rotated_string = right_rotate(s, 2) print(rotated_string) # Output: "efabcd" 

Note: If n is greater than the length of the string, you might want to use n % len(s) instead of n to handle the rotation correctly.

For instance:

def left_rotate(s, n): n %= len(s) return s[n:] + s[:n] def right_rotate(s, n): n %= len(s) return s[-n:] + s[:-n] 

These functions will now handle cases where n is greater than the length of the string.


More Tags

nuxtjs3 selecteditem coffeescript pipe swagger-2.0 fencepost gs-vlookup css dart osx-mavericks

More Programming Guides

Other Guides

More Programming Examples