Regular expression substitution

Hi, Regualar expression substitution does not work for below code. Want to replace whole word ‘mall’ that occurs at the starting of the line with ‘1234’. Any help.

import re

para = ‘’‘ball fall wall tall
mall call ball pall
wall mall ball fall
mallet wallet malls’’’

print( re.sub(’^mall\b’, ‘1234’, para, flags=re.M) )



and you will start to understand. The \b in your pattern is a backspace in Python’s string literal notation. What you want re to see is literally two characters, a \ and a b. So you need an extra backslash:

print(re.sub('^mall\\b', '1234', para, flags=re.M))

Because this is a little inconvenient, you generally want to use the “raw string” notation, by prefixing the string with the letter r.

print(re.sub(r'^mall\b', '1234', para, flags=re.M))

The Regular Expression HOWTO from the documentation has some details: