在python中使用re.sub使字母大写? [英] Making letters uppercase using re.sub in python?

查看:72
本文介绍了在python中使用re.sub使字母大写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多编程语言中,以下内容

In many programming languages, the following

找到 foo([a-z]+)bar 并替换为 GOO\U\1GAR

将导致整个匹配项变为大写.我似乎无法在 python 中找到等价物;存在吗?

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

推荐答案

您可以将函数传递给 re.sub() 这将允许您执行此操作,这是一个示例:

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'

以及使用它的示例:

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

这篇关于在python中使用re.sub使字母大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆