处理包含双引号内的单引号或相反情况的字符串的简单方法是什么?

what is the simple way to handle a string which contains the single quotes inside of the double quotes or in contrary case?

我正在使用 python3.6.

我需要处理文本文件解析出来的字符串,一般情况下顶多出现字符串中包含双引号的情况。 所以我用replace来处理这种情况。

但是我又遇到了一个新的问题,就是文件字段中的单引号空串"''"

例如。

a = '"This is the double quotes in the string"'
# I can handle this simply by
a.replace('"', '')

# But when string is like
b = "''"
b.replace('"', '')
print(b)
>> "''"

#It's ok if I use
b.replace("'", "")
print(b)
>> ""

但是我想请问有没有good/simple方法可以同时处理a和b两种情况

您可以使用 re.sub,它通过正则表达式匹配单引号或双引号 r"[\"\']" 并将它们替换为空字符串

In [5]: re.sub(r"[\"\']",'','"This is the double quotes in the string"')                                                                                                                                                  
Out[5]: 'This is the double quotes in the string'

In [6]: re.sub(r"[\"\']",'',"''")                                                                                                                                                                                         
Out[6]: ''

In [10]: re.sub(r"[\"\']",'','""')                                                                                                                                                                                        
Out[10]: ''

另一种使用 string.replace 的方法,我们用空字符串替换单引号和双引号

In [4]: def replace_quotes(s): 
   ...:  
   ...:     return s.replace('"','').replace("'","") 
   ...:                                                                                                                                                                                                                   

In [5]: replace_quotes("This is the double quotes in the string")                                                                                                                                                         
Out[5]: 'This is the double quotes in the string'

In [6]: replace_quotes("''")                                                                                                                                                                                              
Out[6]: ''

In [7]: replace_quotes('""')                                                                                                                                                                                              
Out[7]: ''