
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- 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
- How to split string by a delimiter string in Python?
- Program to find a good string from a given string in Python
- Python Program to Insert a string into another string
- What is slicing in Python?
- How to capitalize a string in Python?
- How to split a string in Python
- How to reverse a string in Python?
- Program to reverse a list by list slicing in Python
- A unique string in Python
- Program to convert a string to zigzag string of line count k in python
- How to replace all occurrences of a string with another string in Python?

Advertisements