python替换尖括号之间的内容(<>) [英] python replace the content in between angle brackets (<>)

查看:54
本文介绍了python替换尖括号之间的内容(<>)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想替换<>

例如:

输入:这是一个 <测试>

input: this is a < test >

输出:这是一个 <哈 >

output: this is a < hh >

到目前为止我有:

test = 'this is a <test>'
test = re.sub(r'\<[^>]*\>', 'hh', test)
print (test)

这将始终擦除 <> 并产生如下输出:这是一个 hh.但我想要的是:这是一个 <哈>

this will always erase the <> and result an output like: this is a hh. But what I want is: this is a < hh >

我该如何解决它

推荐答案

正如thefourtheye 所建议的,一个解决方案就是这样做

As thefourtheye suggests, one solution is to do

newstr = 'hh'
test = re.sub(r'\<[^>]*\>', '<' + newstr + '>', test)

但我怀疑 re 有更优化的解决方案.

But I suspect a more optimal solution with re.

这篇关于python替换尖括号之间的内容(&lt;&gt;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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