【问题标题】:How to remove quotes from start and end of the string at a specific line in python?如何在python中的特定行从字符串的开头和结尾删除引号?
【发布时间】:2021-11-30 19:54:22
【问题描述】:

我必须替换文件中特定行的字符串,并且当它被替换时,字符串的开头和结尾不应该有引号。

我必须从 file1 中读取内容并将其替换到 file2 中的特定行。

file1.txt:

File1Content - "Replace this line in file"

file2.tf:

var head{
default = File2Content - "This is file2."
}
var tail{
default = "$$Replace Here$$"
}

Python:

with open('file1.txt') as fd:
    file1_text = fd.read()
with open('file2.txt') as fw:
    file2_text = fw.read()
with open('file3.tf' , 'w') as fz:
    fz.write(file2_text.replace("$$Replace Here$$",rep_string))

预期输出:

var head{
default = File2Content - "This is file2."
}
var tail{
default = File1Content - "Replace this line in file"
}

但我得到的是。

输出:

var head{
default = File2Content - "This is file2."
}
var tail{
default = "File1Content - "Replace this line in file""
}

我需要尾块作为 default = File1Content - "Replace this line in file" 我不希望在尾块中字符串的开头和结尾加上引号。有什么想法可以删除吗?

【问题讨论】:

    标签: python string replace quotes


    【解决方案1】:

    尝试替换这一行:

    with open('file3.tf' , 'w') as fz:
        ind.write(file2_text.replace("$$Replace Here$$",rep_string))
    

    用这个:

    with open('file3.tf' , 'w') as fz:
        ind.write(file2_text.replace('"$$Replace Here$$"',rep_string))
    

    【讨论】:

    • 两个代码看起来很相似。
    • 我在双引号前加了单引号
    • 那是因为代码没有替换第二个 tf 文件中的双引号
    • 如果我用单引号替换它,文件中不会发生字符串替换。
    • 不要替换,同时添加。尝试从此处复制并粘贴该行
    【解决方案2】:

    模板文件已经包含引号:

    var head{
    default = File2Content - "This is file2."
    }
    var tail{
    default = "$$Replace Here$$"
    }
    

    如果您不想要它们,请将它们删除:

    var head{
    default = File2Content - "This is file2."
    }
    var tail{
    default = $$Replace Here$$
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      相关资源
      最近更新 更多