Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

267
Views
replace double quotes with '\"' in python

I have a string -

l = '{"a": "1", "b": "2"}'

I want to convert this string to -

'{\"a\": \"1\", \"b\": \"2\"}'

For this I am trying to replace " with \"

Here's what I have tried -

l.replace('\"', '\"')
'{"a": "1", "b": "2"}' 

l.replace('\"', '\\"')
'{\\"a\\": \\"1\\", \\"b\\": \\"2\\"}'

How do I convert {\"a\": \"1\", \"b\": \"2\"}?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Try this:

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

'\"' doesn't mean anything special to Python, so you needn't to add \ before ",if you run

print l.replace('\"', '\\"'),you will get a single backslash too.

Actually what you are seeing is the representation of the string, it's added by repr() method.Python represents backslashes in strings as \\ because the backslash is an Escape Character .

If you print it, you will get single backslash.

You can see more information from String and Bytes literals.

over 4 years ago · Santiago Trujillo Report

0

You can try this also

print l.replace('"',r'\"')

or

print l.replace('"','\\"')
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!