Skip to main content
 首页 » 编程设计

python之使用正则表达式替换括号内的字符

2025年05月04日23telwanggs

我有一个字符串,如下所示:

str = "hello <abc123> python <is456> awesome" 

我想用其他字符替换括号内的字符。像上面的字符串应该给:

"hello lock python lock awesome " 

我试过类似的方法:

ss = str.replace("\\<(.*?)\\>", 'lock')  

但这没有用。那么,我该如何使用正则表达式来做到这一点?

请您参考如下方法:

你可以做一个简单的 regex 替换,比如,

>>> import re 
>>> str = "hello <abc123> python <is456> awesome" 
>>> re.sub(r'<.*?>', 'lock', str) 
'hello lock python lock awesome'