Home > Net >  How to remove quotes from start and end of the string at a specific line in python?
How to remove quotes from start and end of the string at a specific line in python?

Time:10-12

I have to replace a string in a file at specific line and it should not have quotes at start and end of the string when it be replaced.

I have to read the contents from file1 and replace it in file2 at specific line.

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))

Expected Output:

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

But What i'm getting is.

Output:

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

I need tail block as default = File1Content - "Replace this line in file" I don't want that quotes at the start and end of the string in tail block. Any idea to remove it?

CodePudding user response:

try replacing this line:

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

with this:

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

CodePudding user response:

The template file already contains the quotes:

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

If you don't want them, remove them:

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