Display special characters when using print statement

PythonPrintingEscapingCharacter

Python Problem Overview


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"

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIan PhillipsView Question on Stackoverflow
Solution 1 - PythonunutbuView Answer on Stackoverflow
Solution 2 - PythonrobertView Answer on Stackoverflow