Velocity-plus
Velocity-plus

Reputation: 693

Using replace method in Python

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?

Upvotes: 0

Views: 193

Answers (3)

GLHF
GLHF

Reputation: 4035

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.

Upvotes: 0

user2555451
user2555451

Reputation:

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

Upvotes: 1

Irshad Bhat
Irshad Bhat

Reputation: 8709

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

Upvotes: 1

Related Questions