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?
-
Possible duplicate of Reverse a string in Pythonkabanus– kabanus2018-02-04 11:01:19 +00:00Commented Feb 4, 2018 at 11:01
-
2I think reverse is the wrong term here.Mike Müller– Mike Müller2018-02-04 11:08:50 +00:00Commented Feb 4, 2018 at 11:08
Add a comment
|
5 Answers
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'
1 Comment
Jean-François Fabre
I like that answer because it also works with empty strings.
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 +.
2 Comments
Ray
How should I do if the list is numbers? because I got error : unsupported operand type(s) for +: 'int' and 'list'
Mike Müller
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]