0

I'm looking for a way to replace some characters by another one.

For example we have :

chars_to_be_replaced = "ihgr"

and we want them to be replaced by

new_char = "b"

So that the new string

s = "im hungry"

becomes

s' = "bm bunbby".

I'm well aware you can do this one char at a time with .replace or with regular expressions, but I'm looking for a way to go only once through the string.

Does the re.sub goes only once through the string ? Are there other ways to do this ? Thanks

Thanks

Pierre L.
  • 45
  • 1
  • 7

2 Answers2

1

You can use string.translate()

from string import maketrans

chars_to_be_replaced = "ihgr"
new_char = "b"
s = "im hungry"

trantab = maketrans(chars_to_be_replaced, new_char * len(chars_to_be_replaced))

print s.translate(trantab)
# bm bunbby
Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99
0

How about this:

chars_to_be_replaced = "ihgr"
new_char = "b"

my_dict = {k: new_char for k in chars_to_be_replaced}

s = "im hungry"

new_s = ''.join(my_dict.get(x, x) for x in s)
print(new_s)  # bm bunbby

''.join(my_dict.get(x, x) for x in s): for each letter in your original string it tries to get it's dictionary value instead unless it does not exist in which case the original is returned.


NOTE: You can speed it up (a bit) by passing a list to join instead of a generator:

new_s = ''.join([my_dict.get(x, x) for x in s])
Ma0
  • 15,057
  • 4
  • 35
  • 65
  • I've only tested on this small example but it takes more time than to use four times replace. Need to use it on more representative examples – Pierre L. Jun 27 '17 at 09:45