re.sub"( - )"失败了

Tim*_*Tim 1 python string

我无法使用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'
Run Code Online (Sandbox Code Playgroud)

有人可以给我一个提示我做错了什么.

谢谢!

eum*_*iro 6

re.sub(r'my \(-\)', 'your', instr)
Run Code Online (Sandbox Code Playgroud)

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

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

>>> instr = 'Hello, this is my (-) instring'
>>> instr.replace('my (-)', 'your')
'Hello, this is your instring'
Run Code Online (Sandbox Code Playgroud)