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?
As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.
The simplest way to swap the values of two variables is using a temp variable. The temp variables is used to store the value of the fist variable ( temp = a ). This allows you to swap the value of the two variables ( a = b ) and then assign the value of temp to the second variable.
The reversed() Built-in Functionjoin() to create reversed strings. However, the main intent and use case of reversed() is to support reverse iteration on Python iterables. With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With