1

I have the following string:

stringone = '0123456789 abcdefghijklmnopqrstuvwxys ABCDEFGHIJKLMNOPQRSTUVWXYS'

And I need to do the following replaces:

0 = s
1 = 6
2 = r
...
Z = F

But I need to do them in once. I mean, not

stringone.replace('0', 's')
stringone.replace('1', '6')

...not like that, but in one line. Can I do it, for example, like

stringone.replace('0', 's'; '1', '6')

I don't know how to do it. Can you help me? Python 3.6.0

  • Does this answer your question? [How to replace multiple substrings of a string?](https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string) – Alexandre B. Apr 17 '20 at 10:06
  • Partly it does, but I didn't find an answer which would fit for my short code, and after I created this post, I found it easily –  Apr 17 '20 at 10:11

4 Answers4

1

Let's do that with a dictionary:

dic = {'0':'s', '1':'6', '2':'r'....}

# either join
''.join(i if i not in dic else dic[i] for i in stringone)

# or re
import re
re.compile("|".join(dic.keys())).sub(lambda m: dic[re.escape(m.group(0))], stringone)

Join is simpler in that we replace the key with values.

RMPR
  • 3,368
  • 4
  • 19
  • 31
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
0
>>> stringone.translate({ord('0'): 's', ord('1'): '6'})
's623456789 abcdefghijklmnopqrstuvwxys ABCDEFGHIJKLMNOPQRSTUVWXYS'
Badgy
  • 819
  • 4
  • 14
  • Thanks! Just wanted to ask one more question: what does ord mean here? –  Apr 17 '20 at 10:13
  • 1
    ord returns the integer code for the character, because `str.translate` maps those codes to operations. Alternatively for this specific case you could use `stringone.translate(str.maketrans('01', 's6'))` – Masklinn Apr 17 '20 at 10:16
0

Try this below :

import re

def multireplace(string, sub_dict):

    substrings = sorted(sub_dict, key=len, reverse=True)
    regex = re.compile('|'.join(map(re.escape, substrings)))
    return regex.sub(lambda match: sub_dict[match.group(0)], string)

stringone = '0123456789 abcdefghijklmnopqrstuvwxys ABCDEFGHIJKLMNOPQRSTUVWXYS'

sub_dict = {"0": "s", "1": "6", "2":"r","Z":"F"}
output = multireplace(stringone, sub_dict)
Abhishek Kulkarni
  • 1,747
  • 1
  • 6
  • 8
0

Create list of tuples with values to replace:

elements = [('0', 's'), ('1', '6'), ..., ('Z', 'F')]

And then loop over this list:

for to_replace, replacement in elements:
    my_string = my_string.replace(to_replace, replacement)
Grzegorz Pudłowski
  • 477
  • 1
  • 7
  • 14