- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse Only Letters in Python
Suppose we have a string S, we have to find the reversed string where all characters that are not a letter will not change their positions and all letters reverse their positions. So if the given string is "a-bC-dEf-ghIj", then output will be "j-Ih-gfE-dCba"
To solve this, we will follow these steps −
- We will use the regular expression library to solve this
- if S is empty, then return S
- str := an empty string, index1 := 0 and index2 := length of S – 1
- while index1 < length of S
- if index2 >= 0 and S[index1] is alphabet and S[index2] is alphabet
- str := str + S[index2]
- decrease index2 by 1, and increase index1 by 1
- else if S[index1] is alphabet then decrease index2 by 1
- else if S[index1] is not alphabet, then str := str + S[index1], increase index1 by 1
- else decrease index2 by 1, and increase index1 by 1
- if index2 >= 0 and S[index1] is alphabet and S[index2] is alphabet
- return str
Example
Let us see the following implementation to get better understanding −
class Solution: def reverseOnlyLetters(self, S): if not S: return S str_= "" index1 = 0 index2 = len(S)-1 while index1<len(S): #print(index1,index2) if index2>=0 and S[index1].isalpha() and S[index2].isalpha(): str_+=S[index2] index2 -= 1 index1 += 1 elif S[index1].isalpha(): index2-=1 elif not S[index1].isalpha(): str_+=S[index1] index1+=1 else: index2 -= 1 index1 += 1 return str_ ob1 = Solution() print(ob1.reverseOnlyLetters("a-bC-dEf-ghIj"))
Input
"a-bC-dEf-ghIj"
Output
"j-Ih-gfE-dCba"
- Related Articles
- How to check if a string contains only whitespace letters in Python?
- How to check if a string contains only lower case letters in Python?
- How to check if a string contains only upper case letters in Python?
- Python Program to Reverse only First N Elements of a Linked List
- Check if the String contains only unicode letters in Java
- How do I verify that a string only contains letters, numbers, underscores and dashes in Python?
- Reverse only the odd length words - JavaScript
- Reverse Integer in Python
- Reverse String in Python
- How to find If a given String contains only letters in Java?
- Check if the String contains only unicode letters and space in Java
- Check if the String contains only unicode letters or digits in Java
- How to input letters in capital letters in an edit box in Selenium with python?
- How to reverse a given string word by word instead of letters using C#?
- Check if the String contains only unicode letters, digits or space in Java

Advertisements