Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

python - Print escaped representation of a str

How do I print the escaped representation of a string, for example if I have:

s = "String:A"

I wish to output:

String:A

on the screen instead of

String:    A

The equivalent function in java is:

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

from Apache Commons Lang

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You want to encode the string with the string_escape codec:

print s.encode('string_escape')

or you can use the repr() function, which will turn a string into it's python literal representation including the quotes:

print repr(s)

Demonstration:

>>> s = "String:A"
>>> print s.encode('string_escape')
String:A
>>> print repr(s)
'String:A'

In Python 3, you'd be looking for the unicode_escape codec instead:

print(s.encode('unicode_escape'))

which will print a bytes value. To turn that back into a unicode value, just decode from ASCII:

>>> s = "String:A"
>>> print(s.encode('unicode_escape'))
b'String:\tA'
>>> print(s.encode('unicode_escape').decode('ASCII'))
String:A

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...