Making letters uppercase using re.sub in python?

In many programming languages, the following

find foo([az]+)bar and replace with GOOU1GAR

will result in the entire match being made uppercase. I can't seem to find the equivalent in python; does it exist?


You can pass a function to re.sub() that will allow you to do this, here is an example:

 def upper_repl(match):
     return 'GOO' + match.group(1).upper() + 'GAR'

And an example of using it:

 >>> re.sub(r'foo([a-z]+)bar', upper_repl, 'foobazbar')
 'GOOBAZGAR'

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.


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'
链接地址: http://www.djcxy.com/p/74826.html

上一篇: Javascript:负面lookbehind等效?

下一篇: 在Python中使用re.sub使字母大写?