16

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Baz
  • 12,713
  • 38
  • 145
  • 268
  • [This question](http://stackoverflow.com/questions/4202538/python-escape-special-characters) may be of interest to you, though the solution escapes a bit more than what you want.. – m01 Feb 19 '13 at 15:19

5 Answers5

34

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I just want to say again that this is neat. As one who works almost entirely in ASCII, I don't think of encoding very often -- (though I'm trying to be more mindful of that stuff). -- Unfortunately, now that you're the top answer, mine will likely stop getting upvotes ;-). – mgilson Feb 19 '13 at 15:36
  • @mgilson I upvote Martjin's answer because I wasn't aware of the existence of 'string_escape' and mgilson's answer because I'm in a good humor :) – eyquem Feb 19 '13 at 16:03
11

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
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

Give print repr(string) a shot

Sash
  • 4,448
  • 1
  • 17
  • 31
0

As ever, its easy in python:

print(repr(s))
Baz
  • 12,713
  • 38
  • 145
  • 268
0

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

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

>>> print repr(a)
'Hello\tbye\n'
salezica
  • 74,081
  • 25
  • 105
  • 166