Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotating strings in Python

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?

like image 472
Mohit Gidwani Avatar asked Feb 04 '18 10:02

Mohit Gidwani


People also ask

How do you rotate a string in Python?

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.

What is rotating a string?

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".

How do you rotate letters in python?

Use extended string Extend_str, for Left rotation Lfirst = Extended_str[n : l1+n] . For Right rotation Rfirst = str[l1-n : l2-n].

Is there a rotate function in Python?

The collections module has a deque class that provides the rotate(), which is an inbuilt function to allow rotation.


4 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'
like image 63
jpp Avatar answered Oct 24 '22 07:10

jpp


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 +.

like image 21
Mike Müller Avatar answered Oct 24 '22 06:10

Mike Müller


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]
like image 6
Clayton C. Avatar answered Oct 24 '22 08:10

Clayton C.


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
like image 2
Konchog Avatar answered Oct 24 '22 06:10

Konchog