I have a string 'cbbcc',I want to remove 1 of the characters in each round, from left to right, and return the remaining character, like this:
first round: bbcc
second round: cbcc
third round: cbbc
Forth round: cbbc
But if I use the following code:
for i in s:
old_s=s
s=s.replace(i,'')
print(s)
s=old_s
The output will be:
bb
ccc
ccc
bb
bb
Is there anyway I can make the output like:
bbcc
cbcc
cbbc
cbbc
In real business the string can be very very long.
CodePudding user response:
Perhaps you could slice the string, instead of replacing:
for i in range(len(s)):
print(f"{s[:i]}{s[i 1:]}")
Output:
ba
aa
ab
CodePudding user response:
try this
s = 'aba'
for i in range(len(s)):
new_s = s.replace(s[i], "", 1)
print(new_s)