Reputation: 519
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?!!
Upvotes: 0
Views: 2091
Reputation: 572
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.
Upvotes: 1
Reputation: 113948
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.
Upvotes: 4
Reputation: 250931
(
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",'
Upvotes: 2