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

1 Answer

0 votes
def reverse(lst): 
    right = len(lst) - 1
    left = 0
   
    while left < right: 
        if not lst[left].isalpha(): 
            left += 1
        elif not lst[right].isalpha(): 
            right -= 1
        else:  
            lst[left], lst[right] = lst[right], lst[left] 
            left += 1
            right -= 1
   
    return lst
     
 
     
lst = ['a', '#', 'b', '$', '%', 'c', '&', '*', '(', 'd', 'e', 'f', '!']
 
lst = reverse(lst) 
 
print(lst)
 
 
'''
run:
 
['f', '#', 'e', '$', '%', 'd', '&', '*', '(', 'c', 'b', 'a', '!']
 
'''

 



answered Jun 17, 2019 by avibootz
...