2

In an attempt to answer this question, I managed to get the string to print the escape characters by escaping the backslash.

When I try to generalize it to escape all escaped characters, it seems to do nothing:

>>> a = "word\nanother word\n\tthird word" >>> a 'word\nanother word\n\tthird word' >>> print a word another word third word >>> b = a.replace("\\", "\\\\") >>> b 'word\nanother word\n\tthird word' >>> print b word another word third word 

but this same method for specific escape characters, it does work:

>>> b = a.replace('\n', '\\n') >>> print b word\nanother word\n third word >>> b 'word\\nanother word\\n\tthird word' 

Is there a general way to achieve this? Should include \n, \t, \r, etc.

1
  • There are no literal backslashes to match in your strings. The literal contains the two-character sequence \n to specify a newline, but Python converts that to a single, literal linefeed character in the resulting str object. Commented Dec 9, 2016 at 21:28

1 Answer 1

3

Define your string as raw using r'text', like in the code below:

a = r"word\nanother word\n\tthird word" print(a) word\nanother word\n\tthird word b = "word\nanother word\n\tthird word" print(b) word another word third word 
Sign up to request clarification or add additional context in comments.

1 Comment

Raw string are exactly what I was looking for, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.