1

I have a dictionary containing strings with Unicode characters:

d = {'middle': "middle is:\U0001f004."}

For debugging purposes, I'd like to print d and get output with the same notation:

print(d)
{'middle': "middle is:\U0001f004."}

How do I do that?

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
XPlatformer
  • 1,148
  • 8
  • 18

3 Answers3

4

Python 3 has the ascii function for this purpose. Any character outside the ASCII character set is displayed as an escape code:

>>> d = {'middle': "middle is:\U0001f004."}
>>> d
{'middle': 'middle is:.'}
>>> print(ascii(d))
{'middle': 'middle is:\U0001f004.'}
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
1

You can encode the string representation of the dictionary and encode it using unicode_escape. This will return a bytes object that you will want to decode again to get a string.

d = {'middle': 'middle is:\U0001f004.'}
print(str(d).encode('unicode_escape').decode())

Outputs:

{'middle': 'middle is:\U0001f004.'}

This should work for a wide range of situations but, generally speaking, making sure that the printed string matches the code used to create any data structure is not possible.

Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56
0

When outputing the string, encode it with unicode_escape, like this: string.encode('unicode_escape').

jxpp
  • 163
  • 6
  • `d` is a dict. A dict does not have an `encode` method. – XPlatformer Dec 04 '18 at 14:29
  • Correct, you can only call it on the string. You can use a dict comprehension to call it on every key-value pair in the dict: `{k: v.encode('unicode_escape') for k, v in d.items()}`. – jxpp Dec 04 '18 at 14:33
  • this won't work for a list then. Or a dict of dicts. I need something more generic. Debugging stuff with unicode strings in. – XPlatformer Dec 04 '18 at 14:35
  • ...then I get `b"{'middle': 'middle is:\\U0001f004.'}"`. What I asked for was `{'middle': 'middle is:\U0001f004.'}`. Still some way to go... All I need is an easy way to debug-print some variables in my code. – XPlatformer Dec 04 '18 at 14:55
  • At last we know you are using Python3! – Stop harming Monica Dec 04 '18 at 15:12