7

I am trying to switch the first character in a string and move it to the end of the string. It needs to repeat the rotation a number of n times. For example, rotateLeft(hello,2)=llohe.

I tried doing

def rotateLeft(str,n):
    rotated=""
    rotated=str[n:]+str[:n]
    return rotated 

Is this right, and how would you do it if it remove the last character and move it to the front of the string?

3
  • 1
    Maybe you could find something useful in this thread: stackoverflow.com/questions/5781380/… Commented Dec 10, 2011 at 17:07
  • I saw that before, but im trying to do something for all cases Commented Dec 10, 2011 at 17:09
  • "Is this right"... well, did you test it? Commented Dec 10, 2011 at 18:30

3 Answers 3

16

You can shorten it to

def rotate(strg,n):
    return strg[n:] + strg[:n]

and simply use negative indices to rotate "to the right":

>>> rotate("hello", 2)
'llohe'
>>> rotate("hello", -1)
'ohell'
>>> rotate("hello", 1)
'elloh'
>>> rotate("hello", 4)
'ohell'
>>> rotate("hello", -3)
'llohe'
>>> rotate("hello", 6)  # same with -6: no change if n > len(strg)
'hello' 

If you want to keep rotating even after exceeding the length of the string, use

def rotate(strg,n):
    n = n % len(strg)
    return strg[n:] + strg[:n]

so you get

>>> rotate("hello", 1)
'elloh'
>>> rotate("hello", 6)
'elloh'
Sign up to request clarification or add additional context in comments.

Comments

0

The only problem with the code you have posted is the fact that you're trying to use "str" as a name for a string. This is the name of a built in function in Python, and that's why you're getting errors. See more: http://docs.python.org/library/functions.html#str You cannot use that as a name for something.

Changing the name of the string you pass rotateLeft will solve your problem.

def rotateLeft(string,n):
    rotated=""
    rotated=string[n:]+string[:n]
    return rotated

Comments

0

I know this is old, but you can use collections.deque:

from collections import deque

s = 'Impending doom approaches!'
d = deque(s)
d.rotate(11)
print(''.join(d))
>>> approaches!Impending doom
d.rotate(-21)
print(''.join(d))
>>> doom approaches!Impending

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.