Skip to content
Related Articles

Related Articles

Python | Reverse Interval Slicing String

View Discussion
Improve Article
Save Article
  • Last Updated : 23 Jun, 2022

Sometimes, while working with strings, we can have a problem in which we need to perform string slicing. In this, we can have a variant in which we need to perform reverse slicing that too interval. This kind of application can come in day-day programming. Let us discuss certain ways in which this task can be performed.

Method #1: Using String Slicing (1) 

This task can be performed using string slicing, that too nested one. In this, the first slice performs the Interval, and the second slice performs reverse.

Example

Python3




# Python3 code to demonstrate working of
# Reverse Interval Slicing String
# Using String Slicing 1
 
# initializing string
test_str = "geeksforgeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing Interval
K = 2
 
# Reverse Interval Slicing String
# Using String Slicing 1
res = test_str[::K][::-1]
 
# printing result
print("The reverse Interval Slice : " + str(res))

Output

The original string is : geeksforgeeks
The reverse Interval Slice : segoseg

 
Method #2: Using String Slicing (2) 

It is another way in which this task can be performed. In this, we employ similar way as above, but a different kind of slicing.

Python3




# Python3 code to demonstrate working of
# Reverse Interval Slicing String
# Using String Slicing 2
 
# initializing string
test_str = "geeksforgeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing Interval
K = 2
 
# Reverse Interval Slicing String
# Using String Slicing 1
res = test_str[::-1][::K]
 
# printing result
print("The reverse Interval Slice : " + str(res))

Output

The original string is : geeksforgeeks
The reverse Interval Slice : segoseg

Method#3: Using join + list comprehension 

With a specified method, we can perform this task. List comprehension is used to iterate over the string and join method is used to join the list which is formed as a product of list comprehension. 

Python3




# Python3 code to demonstrate working of
# Reverse Interval Slicing String
# Using join + list comprehension
from functools import reduce
# initializing string
test_str = "geeksforgeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# initializing Interval
K = 2
 
# Reverse Interval Slicing String
# Using join and list comprehension
k = "".join( test_str[i] for i in range(len(test_str)-1, -1, -K))
 
# printing result
print("The reverse Interval Slice : " + str(k))

Output

The original string is : geeksforgeeks
The reverse Interval Slice : segoseg

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!