I’m using replace() to distort data, and I’d like to have a “high distortion” setting where every instance is replaced, and a “low distortion” setting where there’s a 50% chance of each instance being replaced. For example:
x = "aaaaaaaaaa"
x = x.replace("a", "b")
'bbbbbbbbbb'
x = "aaaaaaaaaa"
x = x.5050replace("a", "b")
'aabbabbaab'
Without re-writing replace(), how could someone do this?
Use the random module:
This code essentially ‘replaces’ each letter in
xifrandom.randintevaluates to0with'b', and leaves it as it is otherwise.If your string is something for complicated like
'aacakedaaasa'and you only want to replace the'a's, then try this:This doesn’t do anything if the letter isn’t
'a', and if it is, then replaces it with'b'ifrandom.randintreturns0, like the previous example.