John E
John E

Reputation: 49

How can I rotate a string?

How can I rotate a string by two places, e.g. rotate 'MyString' to 'ngMyStri'?

heres my code, I keep getting 'nMyStri'

string = 'MyString'

input("enter the word string: ")
string = string[-2] + string[:-2]
print(string)

Upvotes: 3

Views: 189

Answers (3)

Mykola Zotko
Mykola Zotko

Reputation: 17794

If you want to rotate a string you can convert it to deque and use the method rotate(). After rotating you can join letters to one string using ''.join():

from collections import deque

s = 'ABCDE'

d = deque(s)
print(d)

d.rotate(2)
print(''.join(d))

Output:

deque(['A', 'B', 'C', 'D', 'E'])
DEABC

Upvotes: 0

Rajkamal Tomar
Rajkamal Tomar

Reputation: 15

change line 4 in your code to :

string = string[-2:] + string[:-2]

Explanation : string[-2] returns the second last element of your string, but using ':' will give you the slice from second last element to the end of the string.

Upvotes: 2

gmds
gmds

Reputation: 19885

[-2] gives you the character at the 2nd last position. You want that character onwards to the end of the string:

string = string[-2:] + string[:-2] 
print(string)

Output:

ngMyStri

Upvotes: 3

Related Questions