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
  • return str


Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def reverseOnlyLetters(self, S):
      if not S:
         return S
      str_= ""
      index1 = 0
      index2 = len(S)-1
      while index1<len(S):
         if index2>=0 and S[index1].isalpha() and S[index2].isalpha():
            index2 -= 1
            index1 += 1
         elif S[index1].isalpha():
         elif not S[index1].isalpha():
            index2 -= 1
            index1 += 1
      return str_
ob1 = Solution()