Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

"multi_replace" 

 

########################################################################## 

# 

# multi_replace function 

# 

# By Xavier Defrang. 

# 

# From the Python cookbook: 

# 

# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 

# 

# There's more cool related code at the above site... 

# 

########################################################################## 

 

 

import re 

 

# 

# The simplest, lambda-based implementation 

# 

 

def multiple_replace(dict, text): 

""" 

Replace in 'text' all occurrences of any key in the given 

dictionary by its corresponding value. Returns the new string. 

""" 

 

# Create a regular expression from the dictionary keys 

regex = re.compile("(%s)" % "|".join(map(re.escape, dict.keys()))) 

 

# For each match, look-up corresponding value in dictionary 

return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)