-2

In my project I need to be able to replace a regex in a string to another.

For example if I have 2 regular expressions [a-c] and [x-z], I need to be able to replace the string "abc" with "xyz", or the string "hello adan" with "hello xdxn". How would I do this?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Cody
  • 11
  • 1
  • 4

2 Answers2

0

Try with re.sub

>>>replace = re.sub(r'[a-c]+', 'x','Hello adan')
>>>replace
'Hello xdxn'
>>>re.sub(r'[a-c]+', 'x','Hello bob')
'Hello xox'
0

We build a map and then translate letter by letter. When using get for dictionary then the second argument specifying what to return if not find.

>>> trans = dict(zip(list("xyz"),list("abc")))
>>> trans
{'x': 'a', 'y': 'b', 'z': 'c'}
>>> "".join([trans.get(i,i) for i in "hello xdxn"])
'hello adan'
>>>

Or change the order in trans to go in other direction

>>> trans = dict(zip(list("abc"),list("xyz")))
>>> trans
{'a': 'x', 'b': 'y', 'c': 'z'}
>>> "".join([trans.get(i,i) for i in "hello adan"])
'hello xdxn'
>>>
polkas
  • 3,797
  • 1
  • 12
  • 25