Skip to main content
 首页 » 编程设计

python之re.sub "(-)"失败

2025年05月04日8oomusou

我无法在 Python 中使用 re.sub 替换字符串“(-)”。

>>> instr = 'Hello, this is my instring' 
>>> re.sub('my', 'your', instr) 
'Hello, this is your instring' 
>>> instr = 'Hello, this is my (-) instring' 
>>> re.sub('my (-)', 'your', instr) 
'Hello, this is my (-) instring' 

有人可以给我提示我做错了什么吗。

谢谢!

请您参考如下方法:

re.sub(r'my \(-\)', 'your', instr) 

您必须转义通常用于匹配组的括号。此外,在字符串前面添加一个 r 以使其保持原始状态(因为反斜杠)。

或者根本不使用正则表达式(如果您的替换就这么简单)并且您不必关心很多问题:

>>> instr = 'Hello, this is my (-) instring' 
>>> instr.replace('my (-)', 'your') 
'Hello, this is your instring'