119

I would like to display the escape characters when using print statement. E.g.

a = "Hello\tWorld\nHello World"
print a
Hello   World
Hello World

I would like it to display: "Hello\tWorld\nHello\sWorld"

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Ian Phillips
  • 1,191
  • 2
  • 8
  • 3

2 Answers2

208

Use repr:

a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'

Note you do not get \s for a space. I hope that was a typo...?

But if you really do want \s for spaces, you could do this:

print(repr(a).replace(' ',r'\s'))
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
19

Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r: r"Hello\tWorld\nHello World".

>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World

Also, \s is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.

robert
  • 33,242
  • 8
  • 53
  • 74