Passing a function to re.sub in Python

后端 未结 3 981
囚心锁ツ
囚心锁ツ 2020-11-28 06:44

I have strings that contain a number somewhere in them and I\'m trying to replace this number with their word notation (ie. 3 -> three). I have a function that does this. Th

3条回答
  •  甜味超标
    2020-11-28 07:26

    A solution without lambda

    import re
    
    def convert_func(matchobj):
        m =  matchobj.group(0)
        map = {'7': 'seven',
               '8': 'eight',
               '9': 'nine'}
        return map[m]
    
    line = "7 ate 9"
    new_line =  re.sub("[7-9]", convert_func, line)
    

提交回复
热议问题