I have a string '1a1b1c1d3e3e3e1f1g2h2h1i1j1k1l1m1n4o4o4o4o1p1q2r2r1s2t2t2u2u1v1w1x1y1z'
and I want to remove all of the duplicates of these charterers: 3e, 4o, 2r etc.
How can I do that in Python?
3 Answers
This is a pretty crude way of doing it.
But it seams to do the job without begin to complicated.
This also assumes that it's known character compositions you need to remove. You didn't mention that you need to remove all duplicates, only a set of known ones.
x = '1a1b1c1d3e3e3e1f1g2h2h1i1j1k1l1m1n4o4o4o4o1p1q2r2r1s2t2t2u2u1v1w1x1y1z'
for y in ['3e', '4o', '2r']:
x = x[:x.find(y)+len(y)] + x[x.find(y)+len(y):].replace(y, '')
print(x)
Finds the first occurance of your desired object (3e for instance) and builds a new version of the string up to and including that object, and prepends the string with the rest of the original string but with replacing your object with a empty string.
This is a bit slow, but again, gets the job done.
No error handling here tho so be wary of -1 positions etc.
x = x[:x.find(y)+len(y)] + x[x.find(y)+len(y):].replace(y, '')wherexis your original string andyis the desired duplicates to be removed no matter what cost. Add error handling etc to catch-1positions etc.