Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print string "like" the interactive interpreter?

Tags:

python

string

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?

like image 670
Karel Bílek Avatar asked Dec 25 '22 00:12

Karel Bílek


2 Answers

Oh, that was fast.

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

python -c 'a="d\x04";print repr(a)'
like image 97
Karel Bílek Avatar answered Jan 03 '23 00:01

Karel Bílek


You're looking for repr():

>>> a = 'd\x04'
>>> a
'd\x04'
>>> print(a)
d
>>> repr(a)
"'d\\x04'"
>>> print(repr(a))
'd\x04'
like image 42
Seth Avatar answered Jan 03 '23 01:01

Seth