Baz
Baz

Reputation: 13145

Print escaped representation of a str

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

s = "String:\tA"

I wish to output:

String:\tA

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

Upvotes: 21

Views: 17291

Answers (5)

Martijn Pieters
Martijn Pieters

Reputation: 1124010

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:\tA"
>>> print s.encode('string_escape')
String:\tA
>>> print repr(s)
'String:\tA'

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:\tA"
>>> print(s.encode('unicode_escape'))
b'String:\\tA'
>>> print(s.encode('unicode_escape').decode('ASCII'))
String:\tA

Upvotes: 38

salezica
salezica

Reputation: 77039

print uses str, which processes escapes. You want repr.

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

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

Upvotes: 0

Baz
Baz

Reputation: 13145

As ever, its easy in python:

print(repr(s))

Upvotes: 0

Sash
Sash

Reputation: 4598

Give print repr(string) a shot

Upvotes: 0

mgilson
mgilson

Reputation: 310099

you can use repr:

print repr(s)

demo

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

This will give the quotes -- but you can slice those off easily:

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

Upvotes: 14

Related Questions