and1can
and1can

Reputation: 79

Python replace "" to \" in text

I want to manipulate my text in python. I will use this text to embed as JavaScript data. I need the text in my text file to display exactly as follows. It should have the format I mention below, not only when it prints.

I have text:

""text""

and I want:

\"text\"

with open('phase2.2.1.csv', 'w', newline='') as csvFile: 
    writer = csv.writer(csvFile)
    for b in batches: 
        writer.writerow([b.replace('\n', '').replace('""', '\\"')])

Unfortunately, the above yields

\""text\""

Any help will be much appreciated.

Upvotes: 2

Views: 182

Answers (2)

abarnert
abarnert

Reputation: 365657

If what you're trying to generate is JSON-encoded strings, the right way to do that is to use the json module:

text = json.dumps(text)

If you're trying to generate actual JavaScript source code, that's still almost the right answer. JSON is very close to being a subset of JavaScript—a lot closer than a quick&dirty fix for one error you happen to have noticed so far is going to be.

If you actually want to generate correct JS code for any possible string, you have to deal with the corner cases where JSON is not quite a subset of JS. But nobody ever does (it took years before anyone even noticed the difference in the specs).

Upvotes: 4

honza_p
honza_p

Reputation: 2093

I would suggest:

.replace('""', '\\"')

And it really works, see:

In [8]: x = '""text""'

In [9]: print(x.replace('""', '\\"'))
\"text\"

Upvotes: 6

Related Questions