繁体   English   中英

在python中替换字符串中的单双引号

[英]Replacing single double quote in string in python

给定的字符串是:

str1=
     "sentence1 and  
           sentence2",
     "sentence3 and 
           sentence4",
     "sentence5 and
           sentence6"

所需的输出是:

sentence1 and  
         sentence2;
sentence3 and 
         sentence4;
sentence5 and
         sentence6;

我现在正在使用的编辑过的pythod代码:

       if (replace_string.find('",')!=-1):
                 replace_string=replace_string.replace('",', ';');
                 replace_string=replace_string.replace('"','');

它给了我如下数据,查找可以正常工作,并用“ ;;”代替也可以,但是现在我想摆脱单引号,如下所示:replace_string = replace_string.replace('“',''); 没有删除每个句子开头的那些双引号

“句子1和
SENTENCE2; “句子3和句子4;”句子5和句子6”

如果字符串以段落格式分配。 然后建议使用三重引号。 像这样。

str1 = """
"sentence1 and  
      sentence2",
"sentence3 and 
      sentence4",
"sentence5 and
      sentence6"
"""

然后使用

str1 = str1.replace(r'",', r";") # this replaces ", with ;
str1 = str1.replace(r'"', '') # this replaces " with nothing.
print str1

关于另一个查询:

str1.find("",")!=-1 doesnt work to find ",

它不起作用,因为它将两个参数传递给查找函数,一个参数是空字符串,另一个参数只打开双引号,而没有结束双引号。

在这种情况下,您可以使用r'“;'来使用原始字符串 或使用像这样的转义字符“ \\”;“

replace方法不能在相同的字符串中进行替换,因为字符串是不可变的,所以它会创建一个新的字符串-不会分配给变量的字符串会丢失。 转换也是多余的-您已经有一个字符串。 只是

for idx, line in enumerate(my_list):
    my_list[idx] = line.replace('",', ';'.replace('"', '')

并尽量不要使用Python对象的名称(例如列表 )作为变量名称-这是麻烦的源头

编辑:至于“发现不工作”-您编写它的方式,您应该有一个例外。 为了使事情变得有价值(错过那个),您可以使用Python str对象而不是str1 如果要在带引号的字符串中使用双引号,则可以:

  • 用反斜杠转义

    str1.find( “\\”,“)!= - 1

  • 只需对字符串使用单引号

    str1.find( '”,')!= - 1

那这个呢?

str1 = str1.replace('",', ';')

您缺少作业。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM