Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to move characters in string by X amount

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"

like image 231
FriendlyCoder Avatar asked Dec 05 '22 20:12

FriendlyCoder


1 Answers

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.

like image 172
gtlambert Avatar answered Dec 15 '22 12:12

gtlambert