-2

As in:
data = data.replace(['a', 'b', 'c'], [0, 1, 2])

Given 'a' replace with 0. Given 'b' replace with 1. Given 'c' replace with 2.

I see there is ways to do it with regex, but I want to know if I can do it something like the above.

Currently it's failing, because it thinks I'm trying to replace a list with a list.

BlueSun
  • 7
  • 5

1 Answers1

0

You can use a dictionary to create pairs which you want replace and iterate other dictonary:

replace_pairs = { 'a': '0', 'b': '1', 'c': '2' }

data = 'abcba'

for key, value in replace_pairs.items():
    data = data.replace(key, value)

Output:

>> data = '01210'

I would recommend the regex method, because the runtime is much shorter: How to replace multiple substrings of a string?

micharaze
  • 957
  • 8
  • 25