提问人:bluebud 提问时间:10/12/2021 最后编辑:bluebud 更新时间:10/12/2021 访问量:347
如何在 python 中特定行的字符串开头和结尾删除引号?
How to remove quotes from start and end of the string at a specific line in python?
问:
我必须在特定行处替换文件中的字符串,并且在替换时,字符串的开头和结尾不应有引号。
我必须从 file1 中读取内容并将其替换在 file2 中的特定行。
文件1.txt:
File1Content - "Replace this line in file"
file2.tf:
var head{
default = File2Content - "This is file2."
}
var tail{
default = "$$Replace Here$$"
}
蟒:
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""
}
我需要 tail 块作为默认值 = File1Content - “替换文件中的这一行” 我不希望在 tail 块中字符串的开头和结尾加上引号。有什么想法可以删除它吗?
答:
0赞
marc
10/12/2021
#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))
评论
0赞
bluebud
10/12/2021
这两个代码看起来很相似。
0赞
marc
10/12/2021
我在双引号前添加了单引号
0赞
marc
10/12/2021
这是因为代码没有替换第二个 TF 文件中的双引号
0赞
bluebud
10/12/2021
如果我用单引号替换它,则文件中不会发生字符串替换。
0赞
marc
10/12/2021
不要替换,两者都加。尝试从此处复制并粘贴该行
0赞
tzot
10/12/2021
#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$$
}
上一个:批处理文件将分号替换为引号
下一个:从单词列表中删除引号和双引号
评论