Home > Mobile >  How can I delete characters from a given string? (String manipulation in python)
How can I delete characters from a given string? (String manipulation in python)

Time:10-31

I have a string="aabbcdb", I want to delete the characters which have occurred twice. It would be better if you answer me using Counter module. PS: I want the answer to be 'cdb'. Coz that's what remains when we delete the twice occurring characters.

CodePudding user response:

if you want to delete character in specific position,you can do like this.

def f(string,pos):
    return string[:pos] string[pos 1:]
>>> s='abcd'
>>> f(s,1)
'acd'

CodePudding user response:

you can use a list as a stack to keep track of the previous character and pop off the stack if the current character is the same as the previous

new_string = [string[0]]
i = 0

for char in string[1:]:
    if new_string != [] and new_string[len(new_string)-1] == char:
        new_string.pop(len(new_string)-1)
    else:
        new_string.append(char)
        i  = 1

print("".join(new_string))
  • Related