Exchange letters in a string in python

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

I tried to do

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

Is this correct, and how would you do it if you delete the last character and move it to the beginning of the line?

+6
source share
3 answers

You can shorten it to

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

and just 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 spinning even after exceeding the string length, 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' 
+15
source

The only problem with the code you posted is that you are trying to use "str" ​​as the name for the string. This is the name of the built-in function in Python and why you get errors. More details: http://docs.python.org/library/functions.html#str You cannot use this as a name for something.

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

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

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 
0
source

Source: https://habr.com/ru/post/903523/


All Articles