gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:50:37 25 4
gpt4 key购买 nike

我使用的是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 两种情况。

最佳答案

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

关于python - 处理双引号内包含单引号或相反情况的字符串的简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56595321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com