4

I like the way Python interactive interpreter prints strings, and I want to repeat that specifically in scripts. However, I can't seem to do that.

Example. I can do this in interpreter:

>>> a="d\x04"
>>> a
'd\x04'

However, I cannot replicate this in the python itself

$ python -c 'a="d\x04";print a'
d

I want this because I want to debug a code with a lot of string with similar non-printable characters.

Is there an easy way to do this?

Karel Bílek
  • 36,467
  • 31
  • 94
  • 149

3 Answers3

6

Oh, that was fast.

I can just use repr() functon. That is, in my example,

python -c 'a="d\x04";print repr(a)'
Karel Bílek
  • 36,467
  • 31
  • 94
  • 149
  • 2
    That is exactly what the interactive interpreter uses: if the result of the expression is not `None` it prints the `repr()` – Duncan Dec 25 '14 at 18:02
4

You're looking for repr():

>>> a = 'd\x04'
>>> a
'd\x04'
>>> print(a)
d
>>> repr(a)
"'d\\x04'"
>>> print(repr(a))
'd\x04'
Seth
  • 45,033
  • 10
  • 85
  • 120
0

Make it a raw string (If possible)

$ python -c 'a=r"d\x04";print a'
d\x04
$ python -c 'a="d\x04";print "%r"%a'
d\x04

EDIT

As you said that you cannot make it a raw string, Then you will have to use repr() as stated in the other answer..

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140