I am not able to replace the string "(-)" using re.sub in Python.
>>> 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'
Can somebody please give me a hint what I am doing wrong.
Thank you!
re.sub(r'my \(-\)', 'your', instr)
You have to escape the parenthesis, which are normally used for matching groups. Also, add an r in front of the string to keep it raw (because of backslashes).
Or don't use regexp at all (if your substitution is that simple) and you don't have to care about many issues:
>>> instr = 'Hello, this is my (-) instring'
>>> instr.replace('my (-)', 'your')
'Hello, this is your instring'
You need to escape the '(-)' because it is a regular expression pattern match, as far as the regex engine is concerned. If you're not sure about how to escape, but your string doesn't have any actual patterns but should be interpreted verbatim, you should do:
>>> re.sub(re.escape('my (-)'), 'your', instr)
'Hello, this is your instring'
or if your string is a mix between a "plain" pattern and complex stuff, you can do this:
>>> re.sub('[a-z]{2} %s' % re.escape('(-)'), 'your', instr)
'Hello, this is your instring'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With