Reputation: 103
In python how can I move characters in string by x amount?
For example lets say the input was "hello"
How can I move each character in the string by 1 so the output I get I get is: "ohell"
Upvotes: 4
Views: 33837
Reputation: 11961
You could use:
my_string = 'hello'
my_string = my_string[-1] + my_string[:-1]
print(my_string)
Output
ohell
my_string[-1]
selects the last character in the string ('o'
), and my_string[:-1]
selects all of the string excluding the last character ('hell'
).
To move by x amount you could use:
my_string = my_string[-x:] + my_string[:-x]
my_string[-x:]
selects the last x characters in the string, and my_string[:-x]
selects all of the string excluding the last x characters.
Upvotes: 14