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 Feb 4, 2018 at 10:55
2
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'
answered Feb 4, 2018 at 11:06
jppjpp
152k32 gold badges256 silver badges319 bronze badges
1
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
+
.
answered Feb 4, 2018 at 10:58
Mike MüllerMike Müller
79.3k18 gold badges157 silver badges159 bronze badges
2
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]
answered Mar 18, 2020 at 23:50
Clayton C.Clayton C.
8631 gold badge8 silver badges16 bronze badges
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
answered Aug 30, 2019 at 14:28
KonchogKonchog
1,81018 silver badges21 bronze badges
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.
answered Mar 16, 2019 at 20:59
A string is given, our task is to slicing the string into two way. One is clockwise and another anticlockwise.
1. Left [Or anticlockwise] rotate the given string by d elements [where d pythonprogram Left Rotation: thonprogrampy Right Rotation: ampythonprogr
Updated on 23-Jun-2020 16:09:07
- Related Questions & Answers
- String slicing in C# to rotate a string
- Rotate String in Python
- String slicing in Python to check if a can become empty by recursive deletion
- Program to rotate a string of size n, n times to left in Python
- Python - Ways to rotate a list
- Program to find a good string from a given string in Python
- Program to reverse a list by list slicing in Python
- Python List Comprehension and Slicing?
- Alternate range slicing in list [Python]
- A unique string in Python
- How to reverse a string in Python?
- How to capitalize a string in Python?
- How to split a string in Python
- String Transforms Into Another String in Python
- Rotate Array in Python