You want to encode a string using a codec string_escape:
print s.encode('string_escape')
or you can use a function repr()that turns a string into this python literal representation, including quotation marks:
print repr(s)
Demonstration:
>>> s = "String:\tA"
>>> print s.encode('string_escape')
String:\tA
>>> print repr(s)
'String:\tA'
In Python 3, you are looking for a codec instead unicode_escape:
print(s.encode('unicode_escape'))
which will print the byte value. To return this value to unicode, simply decode it from ASCII:
>>> s = "String:\tA"
>>> print(s.encode('unicode_escape'))
b'String:\\tA'
>>> print(s.encode('unicode_escape').decode('ASCII'))
String:\tA
source
share