-5

How do I change all parenthesis in a string to a minus sign only when the next character immediately following ( is a number?

input: foo (4,301) bar blah (4)% blah (USD)

output: foo -4,301 bar blah -4% blah (USD)

everything that I have found is relating to getting a number and not changing the string...

num = -int(test.translate(None,"(),"))

that's not what I want

jason
  • 2,045
  • 14
  • 72
  • 122

2 Answers2

1

Using re.sub

Ex:

import re
s = "foo (4,301) bar blah (4)% blah (USD)"
print( re.sub(r"\((\d*,?\d*)\)", r"-\1", s) )

Output:

foo -4,301 bar blah -4% blah (USD)
Rakesh
  • 75,210
  • 17
  • 57
  • 95
0
import re
s = 'foo (4,301) bar blah (4)% blah (USD)'
re.sub(r'\((\d[^\)]*)\)', r'-\1', s)
# 'foo -4,301 bar blah -4% blah (USD)'
Sunitha
  • 11,046
  • 2
  • 14
  • 21
  • This will replace `(3 blind mice)` with `-3 blind mice` - are you sure that's the right thing to do? – NickD Jul 06 '18 at 16:45
  • OP had said `change all parenthesis in a string to a minus sign only when the next character immediately following ( is a number`. So I think, thats the right thing to do – Sunitha Jul 06 '18 at 16:52
  • You are right: the OP did say that. But I'm almost certain that that's *not* what was really wanted: the specification was incomplete. – NickD Jul 06 '18 at 16:58
  • I can just answer based on what was specified. Neither me, nor you can speculate on what the OP actually wants – Sunitha Jul 06 '18 at 17:05