Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python正则表达式re.sub错误_Python_Regex - Fatal编程技术网

python正则表达式re.sub错误

python正则表达式re.sub错误,python,regex,Python,Regex,我有一个.csv文件,其中可能混有括号: line = "fdf,dfdf,(1,2,3,4,5),(ss,dd)," 现在我想将所有()替换为“”,使其看起来像这样: line = 'fdf,dfdf,"1,2,3,4,5","ss,dd",' 我的代码是: line=re.sub(',(', ',"', line) line=re.sub('),', '",', line) 但是我得到了这个错误: ... File "/usr/local/Python-2.7/lib/python

我有一个.csv文件,其中可能混有括号:

line = "fdf,dfdf,(1,2,3,4,5),(ss,dd),"
现在我想将所有()替换为“”,使其看起来像这样:

line = 'fdf,dfdf,"1,2,3,4,5","ss,dd",'
我的代码是:

line=re.sub(',(', ',"', line)
line=re.sub('),', '",', line)
但是我得到了这个错误:

 ...
 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
这里怎么了

在正则表达式中有特殊含义。您可以使用
\(
对其进行转义,或使用方括号将其置于
[]

>>> 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",'

简单的字符串替换怎么样

print strs.replace("(",'"').replace(")",'"')
这不需要正则表达式

有些人在遇到问题时会想:“我知道,我会用 现在他们有两个问题


另一个人会考虑这个问题。

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

你要做的是先更换一个pran,然后再更换另一个。

+1向他展示如何使用regex,因为这是他真正要求的。。。