Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display special characters when using print statement

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"

like image 623
Ian Phillips Avatar asked Jun 25 '11 12:06

Ian Phillips


People also ask

How do you not print special characters in Python?

Using 'str. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do you show special characters in a string?

To display them, Java has created a special code that can be put into a string: \". Whenever this code is encountered in a string, it is replaced with a double quotation mark.


1 Answers

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')) 
like image 96
unutbu Avatar answered Sep 28 '22 21:09

unutbu