0

How do I ignore all escape characters in a string?

Fx: \n \t %s

So if I have a string:

text = "Hello \n My Name is \t John"

Now if I print the string the output will be different than the actual string:

Hello
 My Name is      John

How can I print the 'actual string' like this:

Hello \n My Name is \t John

Here is an example, which doesn't work:

text = "Hello \n My Name is \t John"
text.replace('\n', '\\n').replace('\t', '\\t')
print text

This does not work! No difference

I have looked at some topics where you could remove them, but I DO not want that. How do I ignore them? So we can see the actual string?

Velocity-plus
  • 663
  • 1
  • 5
  • 19
  • `str.replace` doesn't work in-place. You have to assign the return value back to your variable. – Aran-Fey Dec 28 '14 at 18:47
  • You asking how to ignore all escape characters, and checked an answer is not about that. Logic! – GLHF Dec 28 '14 at 19:05
  • possible duplicate of [Python: Display special characters when using print statement](http://stackoverflow.com/questions/6477823/python-display-special-characters-when-using-print-statement) – Joe May 03 '15 at 12:55

3 Answers3

1

You can call repr on the string before printing it:

>>> text = "Hello \n My Name is \t John"
>>> print repr(text)
'Hello \n My Name is \t John'
>>> print repr(text)[1:-1]  # [1:-1] will get rid of the ' on each end
Hello \n My Name is \t John
>>>
1

Your method didn't work because strings are immutable. You need to reassign text.replace(...) to text in order to make it work.

>>> text = text.replace('\n', '\\n').replace('\t', '\\t')
>>> print text
Hello \n My Name is \t John
Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36
0

Little but very usefull method, use r :

a=r"Hey\nGuys\tsup?"
print (a)

Output:

>>> 
Hey\nGuys\tsup?
>>> 

So, for your problem:

text =r"Hello\nMy Name is\t John"
text = text.replace(r'\n', r'\\n').replace(r'\t', r'\\t')
print (text)

Output:

>>> 
Hello\\nMy Name is\\t John
>>> 

You have to define text variable AGAIN, because strings are unmutable.

GLHF
  • 3,835
  • 10
  • 38
  • 83