How to reverse a string of characters without affecting the special characters in Python

1 Answer

0 votes
def reverse(s): 
    right = len(s) - 1
    left = 0
  
    while left < right: 
        if not s[left].isalpha(): 
            left += 1
        elif not s[right].isalpha(): 
            right -= 1
        else:  
            lst = list(s)
            lst[left], lst[right] = lst[right], lst[left] 
            s = ''.join(lst)
            left += 1
            right -= 1
  
    return s
    

    
s = "a#b$%c&*(def!"

s = reverse(s) 

print(s)


'''
run:

f#e$%d&*(cba!

'''

 



answered Jun 16, 2019 by avibootz
...