Display special characters when using print statement

Ian Phillips picture Ian Phillips · Jun 25, 2011 · Viewed 128.1k times · Source

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"

Answer

unutbu picture unutbu · Jun 25, 2011

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'))