Search code examples
pythonpython-3.xstringdouble-quotessingle-quotes

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


I'm using python3.6.

I need to handle the string which comes from the text file parsing, normally, at most, there're the cases which contain double quotes in a string. So I use replace to handle the case.

But I encounter a new problem which is the single quotes empty string "''" in the field of the file.

for example.

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)
>> ""

But I'd like to ask is there a good/simple way to handle a and b two cases simultaneously.


Solution

  • You can use re.sub, which matches either single or double quotes, via regex r"[\"\']" and replaces them with an empty string

    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]: ''
    

    Another approach using string.replace, where we replace single and double quotes with empty string

    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]: ''