Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
String slicing in Python to rotate a string
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 <= n).
2. Right (Or clockwise) rotate the given string by d elements (where d <= n).
Example
Input: string = "pythonprogram" d = 2 Output: Left Rotation: thonprogrampy Right Rotation: ampythonprogr
Algorithm
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.
Example Code
def rotate(input,d):
# Slice string in two parts for left and right
Lfirst = input[0 : d]
Lsecond = input[d :]
Rfirst = input[0 : len(input)-d]
Rsecond = input[len(input)-d : ]
print ("Left Rotation : ", (Lsecond + Lfirst) )
print ("Right Rotation : ", (Rsecond + Rfirst) )
# Driver program
if __name__ == "__main__":
str = input("Enter String ::>")
d=2
rotate(str,d)
Output
Enter String ::> pythonprogram Left Rotation: thonprogrampy Right Rotation: ampythonprogr
Advertisements