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?
Asked
Active
Viewed 3.7k times
11

Karl Knechtel
- 62,466
- 11
- 102
- 153

Mohit Gidwani
- 123
- 1
- 1
- 6
-
Possible duplicate of [Reverse a string in Python](https://stackoverflow.com/questions/931092/reverse-a-string-in-python) – kabanus Feb 04 '18 at 11:01
-
2I think *reverse* is the wrong term here. – Mike Müller Feb 04 '18 at 11:08
5 Answers
16
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'

jpp
- 159,742
- 34
- 281
- 339
-
2I like that answer because it also works with empty strings. – Jean-François Fabre Nov 10 '18 at 18:12
10
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 +
.

Mike Müller
- 82,630
- 20
- 166
- 161
-
How should I do if the list is numbers? because I got error : unsupported operand type(s) for +: 'int' and 'list' – Ray Dec 17 '18 at 17:17
-
This is for strings. Maybe you men a list of numbers `[1, 2, 3]`? `>>> L = [1, 2, 3] >>> L[-1:] + L[:-1] [3, 1, 2]` – Mike Müller Dec 17 '18 at 17:38
6
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]

Clayton C.
- 863
- 1
- 8
- 17
2
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

Konchog
- 1,920
- 19
- 23
0
I would agree with Mike Müller's answer:
s = 'HELLO'
s = s[-1] + s[:-1]
I would like to share another way of looking at s[:-1]
s[0:-1]
This means that it is starting from the start and including everything except for s[-1]. I hope this helped.

Surya Kannan KMS
- 31
- 11