Printing a shielded view str

How to print an escaped string representation, for example if I have:

s = "String:\tA"

I want to output:

String:\tA

on screen instead

String:    A

Equivalent function in java:

String xy = org.apache.commons.lang.StringEscapeUtils.escapeJava(yourString);
System.out.println(xy);

from Apache Commons Lang

+5
source share
5 answers

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
+16
source

you can use repr:

print repr(s)

demo

>>> s = "String:\tA"
>>> print repr(s)
'String:\tA'

, :

>>> print repr(s)[1:-1]
String:\tA
+8

Give a print repr(string)picture

0
source

As always, its easy in python:

print(repr(s))
0
source

printuses strthat handles escape sequences. You want to repr.

>>> a = "Hello\tbye\n"
>>> print str(a)
Hello   bye

>>> print repr(a)
'Hello\tbye\n'
0
source

All Articles