Python | Reverse Incremental String Slicing

Sometimes, while working with Pythonn strings, we can have a problem in which we need to perform the slice and print of strings in reverse order. This can have application in day-day programming. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is brute force way in which this task can be performed. In this, we iterate the list in reverse order and store the incremental strings in list.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Reverse Incremental String Slicing
# Using loop
  
# initializing string
test_str = "geeks"
  
# printing original string
print("The original string is : " + test_str)
  
# Reverse Incremental String Slicing
# Using loop
res = []
sub = ''
for chr in reversed(test_str):
    sub += chr
    res.append(sub)
  
# printing result 
print("The incremental reverse strings : " + str(res)) 

chevron_right


Output :

The original string is : geeks
The incremental reverse strings : ['s', 'sk', 'ske', 'skee', 'skeeg']

 

Method #2 : Using list slicing + list comprehension
This is yet another way in which this task can be performed. In this, we iterate the string list using list comprehension and slicing is used to perform incremental slicing.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Reverse Incremental String Slicing
# Using list comprehension + list slicing
  
# initializing string
test_str = "geeks"
  
# printing original string
print("The original string is : " + test_str)
  
# Reverse Incremental String Slicing
# Using list comprehension + list slicing
res = [test_str[-1 : idx : -1] for idx in range(-2, -2 - len(test_str), -1)]
  
# printing result 
print("The incremental reverse strings : " + str(res)) 

chevron_right


Output :

The original string is : geeks
The incremental reverse strings : ['s', 'sk', 'ske', 'skee', 'skeeg']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.