Given a string with punctuations, perform string reverse, leaving punctuations at their places.
Input : test_str = ‘geeks@#for&%%gee)ks’
Output : skeeg@#rof&%%ske)eg
Explanation : Whole string is reveresed, except the punctuations.
Input : test_str = ‘geeks@#for&%%gee)ks’ [ only substring reversal ]
Output : skeeg@#rof&%%eeg)sk
Explanation : Only substrings are reversed.
Method #1 : Using loop + stack + punctuation + split()
In this, we use stack to perform string reversal, checking for punctuation, if current character is one, we append that. The split method is used to handle cases of spaces, which needs to be ignored while reverse.
The original string is : geeks#for&%%gee)ks The Reversed String ignoring punctuation : skeeg#rof&%%ske)eg
Method #2 : Using groupby() + isalnum() [ for substing specific reversal ]
In this, we form grouping of each of substring between punctuations, and reverse them among them, not whole. The isalnum() is used to check for all alphabets
The original string is : geeks#for&%%gee)ks The Reversed String ignoring punctuation [substring] : skeeg#rof&%%eeg)sk
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course