Making letters uppercase using re.sub in python?

后端 未结 5 966
死守一世寂寞
死守一世寂寞 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 08:02

    If you already have a replacement string (template), you may not be keen on swapping it out with the verbosity of m.group(1)+...+m.group(2)+...+m.group(3)... Sometimes it's nice to have a tidy little string.

    You can use the MatchObject's expand() function to evaluate a template for the match in the same manner as sub(), allowing you to retain as much of your original template as possible. You can use upper on the relevant pieces.

    re.sub(r'foo([a-z]+)bar', lambda m: 'GOO' + m.expand('\1GAR').upper())
    

    While this would not be particularly useful in the example above, and while it does not aid with complex circumstances, it may be more convenient for longer expressions with a greater number of captured groups, such as a MAC address censoring regex, where you just want to ensure the full replacement is capitalized or not.

提交回复
热议问题