A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/string-slicing-python-rotate-string/ below:

String slicing in Python to Rotate a String

String slicing in Python to Rotate a String

Last Updated : 05 Mar, 2025

Given a string of size n, write functions to perform following operations on string:

For example, let's take a string s = "GeeksforGeeks" and d = 2, so for this example, our Left Rotation will be "eksforGeeksGe" and Right Rotation will be "ksGeeksforGee". Let's discuss some of the ways to do it with examples.

Using Slicing

Python’s string slicing provides a quick way to rotate strings. The idea is to divide the string into two parts and rearrange them to get the desired rotation.

Python
s = "GeeksforGeeks"
d = 2

# Left Rotation
left = s[d:] + s[:d]

# Right Rotation
right = s[-d:] + s[:-d]

print("Left Rotation:", left)
print("Right Rotation:", right)

Output
Left Rotation: eksforGeeksGe
Right Rotation: ksGeeksforGee

Explanation:

By Extending the String

Create an extended string by concatenating 's + s' as it will cointain all possible rotations and then extract the rotated substring by slicing within the extended string.

Python
s = "GeeksforGeeks"
d = 2

# Create extended string
ext_s = s + s
n = len(s)

# Left Rotation
left = ext_s[d:n + d]

# Right Rotation
right = ext_s[n - d: 2 * n - d]

print("Left Rotation:", left)
print("Right Rotation:", right)

Output
Left Rotation: eksforGeeksGe
Right Rotation: ksGeeksforGee

Explanation:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4