Python re.sub(): how to substitute all 'u' or 'U's with 'you'

后端 未结 5 1096
暖寄归人
暖寄归人 2021-01-30 03:19

I am doing some text normalization using python and regular expressions. I would like to substitute all \'u\'or \'U\'s with \'you\'. Here is what I have done so far:

         


        
5条回答
  •  情歌与酒
    2021-01-30 03:50

    This worked for me:

        import re
        text = 'how are u? umberella u! u. U. U@ U# u '
        rex = re.compile(r'\bu\b', re.IGNORECASE)
        print(rex.sub('you', text))
    

    It pre-compiles the regular expression and makes use of re.IGNORECASE so that we don't have to worry about case in our regular expression! BTW, I love the funky spelling of umbrella! :-)

提交回复
热议问题