Making letters uppercase using re.sub in python?

后端 未结 5 965
死守一世寂寞
死守一世寂寞 2020-11-30 07:26

In many programming languages, the following

find foo([a-z]+)bar and replace with GOO\\U\\1GAR

will result in the entire match bei

5条回答
  •  [愿得一人]
    2020-11-30 07:50

    You could use some variation of this:

    s = 'foohellobar'
    def replfunc(m):
         return m.groups()[0]+m.groups()[1].upper()+m.groups()[2]
    re.sub('(foo)([a-z]+)(bar)',replfunc,s)
    

    gives the output:

    'fooHELLObar'
    

提交回复
热议问题