0

I have a .csv files that might have brackets mixed in:

line = "fdf,dfdf,(1,2,3,4,5),(ss,dd),"

Now I want to replace all the () with "", so that it looks like this:

line = 'fdf,dfdf,"1,2,3,4,5","ss,dd",'

My code is:

line=re.sub(',(', ',"', line)
line=re.sub('),', '",', line)

However I got this error:

 ...
 File "/usr/local/Python-2.7/lib/python2.7/re.py", line 151, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/local/Python-2.7/lib/python2.7/re.py", line 242, in _compile
    raise error, v # invalid expression
sre_constants.error: unbalanced parenthesis

What is wrong here?!!

3 Answers 3

4

how bout just simple string substitution

print strs.replace("(",'"').replace(")",'"')

no need for regex for this

Some people, when confronted with a problem, think “I know, I'll use regular expressions.” Now they have two problems.

0
2

( have special meaning in regular expressions you can escape them using \( or place them use square [] brackets.

>>> import re
>>> strs = "fdf,dfdf,(1,2,3,4,5),(ss,dd),"
>>> re.sub(r"[()]",'"',strs)
'fdf,dfdf,"1,2,3,4,5","ss,dd",'
#or
>>> re.sub(r"\(|\)",'"',strs)
'fdf,dfdf,"1,2,3,4,5","ss,dd",'
1
  • +1 for showing him how to do it with regex since thats what he actually asked for ... Commented May 16, 2013 at 18:41
1

another one would be to consider this..

import re 
re.sub('\)', '\"', re.sub('\(', '\"', line))

what you do is replace one pran once and then replace the other one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.