I was trying to make the string HELLO
to OHELL
in Python. But couldn't get any way to rotate it without working with loops. How to code for it in just 1-2 lines so that I could get the desired pattern?
Step 1: Enter string. Step 2: Separate string in two parts first & second, for Left rotation Lfirst = str[0 : d] and Lsecond = str[d :]. For Right rotation Rfirst = str[0 : len(str)-d] and Rsecond = str[len(str)-d : ]. Step 3: Now concatenate these two parts second + first accordingly.
A String is said to be a rotation of another String, if it has the same length, contains the same characters, and they were rotated around one of the characters. For example, String"bcda" is a rotation of "abcd" but "bdca" is not a rotation of String "abcd".
Use extended string Extend_str, for Left rotation Lfirst = Extended_str[n : l1+n] . For Right rotation Rfirst = str[l1-n : l2-n].
The collections module has a deque class that provides the rotate(), which is an inbuilt function to allow rotation.
Here is one way:
def rotate(strg, n):
return strg[n:] + strg[:n]
rotate('HELLO', -1) # 'OHELL'
Alternatively, collections.deque
("double-ended queue") is optimised for queue-related operations. It has a dedicated rotate() method:
from collections import deque
items = deque('HELLO')
items.rotate(1)
''.join(items) # 'OHELL'
You can slice and add strings:
>>> s = 'HELLO'
>>> s[-1] + s[:-1]
'OHELL'
This gives you the last character:
>>> s[-1]
'O'
and this everything but the last:
>>> s[:-1]
'HELL'
Finally, add them with +
.
Here is what I use to rotate strings in Python3:
To rotate left by n:
def leftShift(text,n):
return text[n:] + text[:n]
To rotate right by n:
def rightShift(text,n):
return text[-n:] + text[:-n]
Here is a simple way of looking at it...
s = 'HELLO'
for r in range(5):
print(s[r:] + s[:r])
HELLO
ELLOH
LLOHE
LOHEL
OHELL
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