Search code examples
pythonstringfor-loopenumerate

string index not getting updated in a loop


I am parsing a string for spaces and i find that the string index is not getting updated even after updating the string, where am i wrong ? will be very happy for any guidance provided

class Palindrome:
    
    def __init__(self,seq):
        self.seq=seq.lower()
        
    def remove_space(self):
        print('up',self.seq)
        for num,i in enumerate(self.seq):
            print('start',self.seq)
            if i==' ':
                print('orig',(num,i))
                new_seq=self.seq[:num]+self.seq[num+1:]  
                num=num+1
                self.seq=new_seq # updating the string here
                print('now',self.seq)
                print(num)
        #print(new_seq)        
seq1=Palindrome('superman is here')           
seq1.remove_space() ```

Solution

  • If you want to proceed with your method, you need to account for the number of spaces you've already removed from the string. And I also included an alternative way of removing space while still using a loop.

    class Palindrome:
        
        def __init__(self,seq):
            self.seq=seq.lower()
            
        def remove_space_alt(self):
            print(self.seq)
            temp_string = ''
            for i, letter in enumerate(self.seq):
                if letter != ' ':
                    temp_string += letter
            self.seq = temp_string
            print(self.seq)
            
        def remove_space(self):
            print(self.seq)
            space_count = 0
            for i, letter in enumerate(self.seq):
                if letter == ' ':
                    first = self.seq[:i - space_count]
                    second = self.seq[i + 1 - space_count:]
                    space_count += 1
                    self.seq = first + second
                    print(self.seq)
    
    
    print('Showing remove_space')       
    seq1=Palindrome('superman is here')
    seq1.remove_space()
    
    print('\nShowing remove_space_alt')
    seq1=Palindrome('superman is here')
    seq1.remove_space_alt()
    

    Output:

    Showing remove_space
    superman is here
    supermanis here
    supermanishere
    
    Showing remove_space_alt
    superman is here
    supermanishere
    

    Original Post: Suggested using string replace() to remove spaces, and did not fully explain issue with changing for-loop index mid loop.