In Python, the easiest way to rotate characters in a string is with slicing. You can rotate a string backwards or forwards with slicing.
string = "hello"
string_rotated_backwards = string[1:] + string[:1]
string_rotated_forward = string[-1:] + string[:-1]
print(string_rotated_backwards)
print(string_rotated_forward)
#Output:
elloh
ohell
In Python, strings are one of the most used data structures. When working with strings, it is useful to be able to change the order of characters of a string in an easy way.
With Python, we can easily rotate the characters in a string both to the right or the left.
To rotate a string backwards, we slice the string from the second character to the end, and then add a slice with only the first character to the end of first slice.
To rotate a string forward, we slice the string from the second to last character to the beginning, and then add a slice with only the last character to the beginning of first slice.
Below is an example of how to rotate a string both backwards and forward with string slicing using Python.
string = "hello"
string_rotated_backwards = string[1:] + string[:1]
string_rotated_forward = string[-1:] + string[:-1]
print(string_rotated_backwards)
print(string_rotated_forward)
#Output:
elloh
ohell
If you need to rotate a string multiple times, we can define a function which rotates the string a specified number of characters.
Below is a function which will rotate the characters in a string using slicing multiple times to the left or right depending on the argument values passed.
def rotateString(string,direction,n):
if direction == "backwards":
new_string = string[n:] + string[:n]
else:
new_string = string[-n:] + string[:-n]
return new_string
print(rotateString("progrmaming","backwards",2))
print(rotateString("progrmaming","forwards",3))
#Output:
ogrmamingpr
ingprogrmam
Hopefully this article has been useful for you to learn how to rotate strings in Python.