python: write 'backslash double-quote' str

2019-07-11 18:05发布

问题:

I've got an input file with some string containing double quotes in it, and want to generate a C-style header file with Python.

Say,

input file: Hello "Bob"
output file: Hello \"Bob\"

I can't write the code to obtain such a file, here's what I've tried so far:

key = 'key'
val = 'Hello "Bob"'
buf_list = list()
...
val = val.replace('"', b'\x5c\x22')
# also tried: val = val.replace('"', r'\"')
# also tried: val = val.replace('"', '\\"')
buf_list.append((key + '="' + val + '";\n').encode('utf-8'))
...
for keyval in buf_list:
    lang_file.write(keyval)
lang_file.close()

The output file always contains:

Hello \\\"Bob\\\"

I had no problems writing \n, \t strings into the output file.

It seems I can only write zero or two backslashes, can someone help please ?

回答1:

You need to escape both the double-quote and the backslash. The following works for me (using Python 2.7):

with open('temp.txt', 'r') as f:
    data = f.read()

with open('temp2.txt', 'w') as g:
    g.write(data.replace('\"', '\\\"'))


回答2:

The conversion of string to raw string during replacement should do.

a='Hello "Bob"'
print a.replace('"', r'\"')

The above will give you: Hello \"Bob\"