Display special characters when using print statement Display special characters when using print statement python python

Display special characters when using print statement


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


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 aHello\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.