How do I delete every occurrence of a character after the first occurrence in a string

Viewed 114
test = "abcdefbdbob"

How would I delete all occurrences of "b" after the first b?

6 Answers

You can add your characters to a result list and then join it back at the end (this removes all duplicate characters after the first one), e.g.:

In []:
result = []
for c in test:
    if c in result:
        continue
    result.append(c)

''.join(result)

Out[]:
'abcdefo'

You can do this in a list comprehension but it is a bit of hack with a helper set(), e.g.:

In []:
seen = set()
''.join(seen.add(c) or c for c in test if c not in seen)

Out[]:
'abcdefo'

I would be tempted to just partition on the character, then join back the halfs with b and replace in the second half:

test = "abcdefbdbob"

first, sep, rest = test.partition('b')

sep.join([first, rest.replace(sep, '')])
# 'abcdefdo'

You can use:

test[:test.find('b')+1] + test[test.find('b')+1:].replace('b','')

Try :

test = test[:test.index("b")+1:] +[test.index("b")+1::].replace("b", "") 

It will work

You can use the find method to find the index of the first occurrence of b then use that index to create two slices. The first slice is up to and including the index and the second one starting from the next index up to the end of the string with b replaced using the replace method then combine the two slices.

So something like

test = "abcdefbdbob"
i = test.find('b')
print(test[:i+1] + test[i+1:].replace('b', '')) # abcdefdo

Try this:

test[::-1].replace("b","",test.count("b")-1)[::-1]
Related