0

I'm' trying to convert string to JSON file using the json.dump method. Before the conversion, I need to add escape character before each char that represented as hex for example '\x00' or '\x96'.

In the end I need to convert string like:

'\x94\xa0aaa'

To:

'\\x94\\xa0aaa'

How can I do it? I tried to use the replace method, but it didn't work.

  • Possible duplicate of [python replace single backslash with double backslash](https://stackoverflow.com/questions/17327202/python-replace-single-backslash-with-double-backslash) – Nikaido Mar 08 '18 at 15:45
  • *I need to convert...* No, you don't, json knows about that: `json.dumps('\x94\xa0aaa')` directly gives: `'"\\u0094\\u00a0aaa"'` – Serge Ballesta Mar 08 '18 at 15:46

4 Answers4

1

The backslash has a special meaning in Python. If you define a literal string like '\x94\xa0aaa' there is no real backslash in it. If you define it raw like r'\x94\xa0aaa' there are real backslashes.

In your replace() call you have to double the backslashes because raw strings can not end with a backslash.

jhinghaus
  • 770
  • 10
  • 27
0

Try this:

import re
old = r'\x94\xa0aaa'
new = re.sub(r"\\", r"\\\\", old)
print(new)

Result:  \\x94\\xa0aaa
jose_bacoy
  • 12,227
  • 1
  • 20
  • 38
0

Of course it didn't. The first line is the representation of one string, the second one is the representation of another one.

This is what you can do:

a = '\x94\xa0aaa' # displays as '\x94\xa0aaa', but indeed contains 94 and a0 in hex, followed by three "a", so 94a0616161
b = a.repr() # displays as '\\x94\\xa0aaa', but indeed contains '\x94\xa0aaa', i. e. 5c7839345c786130616161.
glglgl
  • 89,107
  • 13
  • 149
  • 217
0

Try this:

bs = chr(92)
print(r"\x94\xa0aaa".replace(bs,bs*2))

92 stands for \ ascii number.

Abe
  • 1,357
  • 13
  • 31