字符串索引没有在循环中更新

string index not getting updated in a loop

我正在解析字符串中的空格,我发现即使在更新字符串后字符串索引也没有更新,我哪里错了?将非常高兴提供任何指导

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() ```

如果您想继续您的方法,您需要考虑您已经从字符串中删除的 space 的数量。我还提供了一种在仍然使用循环的同时删除 space 的替代方法。

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()

输出:

Showing remove_space
superman is here
supermanis here
supermanishere

Showing remove_space_alt
superman is here
supermanishere

原文Post:建议使用string replace()删除spaces,并没有完全解释在循环中更改for循环索引的问题。