user12828597
user12828597

Reputation:

How to do multiple replaces at once? | PYTHON

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

Upvotes: 1

Views: 86

Answers (4)

Joshua Varghese
Joshua Varghese

Reputation: 5202

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.

Upvotes: 1

Grzegorz Pudłowski
Grzegorz Pudłowski

Reputation: 537

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)

Upvotes: 0

Abhishek Kulkarni
Abhishek Kulkarni

Reputation: 1767

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)

Upvotes: 0

Badgy
Badgy

Reputation: 819

>>> stringone.translate({ord('0'): 's', ord('1'): '6'})
's623456789 abcdefghijklmnopqrstuvwxys ABCDEFGHIJKLMNOPQRSTUVWXYS'

Upvotes: 0

Related Questions