1

I am interested in finding any occurrence of

(somenumber)

and replacing it with

-somenumber

I have a Perl background and tried this, hoping the (\d+) grouping would populate variable $1:

myterm = re.sub(r"\((\d+)\)", "-\$1",myterm)

However this resulted in a result of the literal

-$1 

How to do this in Python?

2
  • 1
    try r"-\1" instead Commented Jan 9, 2018 at 23:01
  • 1
    Use a raw string: r"-\1" and no $. Commented Jan 9, 2018 at 23:01

1 Answer 1

1

I see two problems:

  1. You're using Perl's syntax (dollar sign) to dereference the positional match. Python uses \, not $.

  2. Your backslash in "-\$1 is being interpreted by the Python compiler, and is effectively removed before re.sub sees it.

Either using a raw string (as noted in the comments to your question), or escaping the backslash (by double-backslashing), should fix it:

myterm = re.sub(r"\((\d+)\)", r"-\1", myterm)

or

myterm = re.sub(r"\((\d+)\)", "-\\1", myterm)

Tested and confirmed:

import re

myterm = '(1234)'

# OP's attempt:
print re.sub(r"\((\d+)\)", "-\$1", myterm)

# two ways to fix:
print re.sub(r"\((\d+)\)", r"-\1", myterm)
print re.sub(r"\((\d+)\)", "-\\1", myterm)

prints:

-\$1
-1234
-1234
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.