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?

3
  • str.replace doesn't work in-place. You have to assign the return value back to your variable. Commented Dec 28, 2014 at 18:47
  • You asking how to ignore all escape characters, and checked an answer is not about that. Logic! Commented Dec 28, 2014 at 19:05
  • possible duplicate of Python: Display special characters when using print statement Commented May 3, 2015 at 12:55

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.