Making letters uppercase using re.sub in python?

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

    Do you mean something like this?

    >>>x = "foo spam bar"
    >>>re.sub(r'foo ([a-z]+) bar', lambda match: r'foo {} bar'.format(match.group(1).upper()), x)
    'foo SPAM bar'
    

    For reference, here's the docstring of re.sub (emphasis mine).

    Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.

提交回复
热议问题