Python | Reverse Slicing of given string
Sometimes, while working with strings we might have a problem in which we need to perform the reverse slicing of string, i.e slicing the string for certain characters from the rear end. Let’s discuss certain ways in which this can be done.
Method #1 : Using join() + reversed()
The combination of above function can be used to perform this particular task. In this, we reverse the string in memory and join the sliced no. of characters so as to return the string sliced from rear end.
# Python3 code to demonstrate working of # Reverse Slicing string # Using join() + reversed() # initializing string test_str = "GeeksforGeeks" # printing original string print("The original string is : " + test_str) # initializing K K = 7 # Using join() + reversed() # Reverse Slicing string res = ''.join(reversed(test_str[0:K])) # printing result print("The reversed sliced string is : " + res) |
The original string is : GeeksforGeeks The reversed sliced string is : ofskeeG
Method #2 : Using string slicing
The string slicing can be used to perform this particular task, by using “-1” as the third argument in slicing we can make function perform the slicing from rear end hence proving to be a simple solution.
# Python3 code to demonstrate working of # Reverse Slicing string # Using string slicing # initializing string test_str = "GeeksforGeeks" # printing original string print("The original string is : " + test_str) # initializing K K = 7 # Using string slicing # Reverse Slicing string res = test_str[(K-1)::-1] # printing result print("The reversed sliced string is : " + res) |
The original string is : GeeksforGeeks The reversed sliced string is : ofskeeG
Recommended Posts:
- Python Slicing | Reverse an array in groups of given size
- String slicing in Python to check if a string can become empty by recursive deletion
- Python | Get the substring from given string using list slicing
- String slicing in Python to rotate a string
- Reverse string in Python (5 different ways)
- Reverse words in a given String in Python
- Python | Custom slicing in List
- Python List Comprehension and Slicing
- Python | Variable list slicing
- Interesting facts about strings in Python | Set 2 (Slicing)
- Python Slicing | Extract ‘k’ bits from a given position
- Python | Alternate range slicing in list
- Basic Slicing and Advanced Indexing in NumPy Python
- Program to cyclically rotate an array by one in Python | List Slicing
- Python | Slicing list from Kth element to last element
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.



