-5

I am new to python programming and would like to write a program which has the following requirement:

The program accepts an input string and the number of rotations. Rotate all characters in the string and print the result on screen.

For example, input is ABCDZ 3 Then, output is DEFGC

def rotate(input,d): 

Rfirst = input[0 : len(input)-d] 
Rsecond = input[len(input)-d : ] 

print "Right Rotation : ", (Rsecond + Rfirst) 

However, I have written a few codes by myself and turned out that I could only rotate the character within ABCDZ to e.g. ZABCD instead of the rotation pattern dictated in the requirement.

Would anyone like to give help on the issue? How should I start with the correct direction? Thank you very much to all of you. I am really frustrated..

Chun Tsz
  • 55
  • 2

1 Answers1

0

Could this work?

def rotate_str(mstr, n):
  reverse = False
  if n < 0:
    n, reverse = - n, True
  for _ in range (0,n):
    if not reverse: mstr = mstr[-1] + mstr[0:-1]
    if reverse: mstr = mstr[1:] + mstr[0]
  return mstr

Negative n reverses the direction of rotation.

mstr = 'ABCDZ'
print(rotate_str(mstr, 3)) #=> CDZAB
print(rotate_str(mstr, -4)) #=> ZABCD
iGian
  • 11,023
  • 3
  • 21
  • 36