【问题标题】:what is the simple way to handle a string which contains the single quotes inside of the double quotes or in contrary case?处理包含双引号内的单引号或相反情况的字符串的简单方法是什么?
【发布时间】:2019-06-14 09:31:55
【问题描述】:

我正在使用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)
>> ""

但我想问一下有没有一种好的/简单的方法可以同时处理 a 和 b 两种情况。

【问题讨论】:

  • 使用方法链。例如:str.replace('"', '').replace("'", "")

标签: python python-3.x string double-quotes single-quotes


【解决方案1】:

您可以使用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]: ''

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 2015-09-16
    • 2014-09-26
    • 1970-01-01
    相关资源
    最近更新 更多