0

I need to doubly escape all escaped characters in a string in python. So, for example, any instances of '\n' need to be replaced by '\\n' I can easily do this one character at a time with

s = s.replace('\n', '\\n')
s = s.replace('\r', '\\r')
# etc...

But I'm wondering if there's a one-off way to handle all of them.

ewok
  • 20,148
  • 51
  • 149
  • 254
  • Related question, [Escape special characters in a Python string - Stack Overflow](https://stackoverflow.com/questions/4202538/escape-special-characters-in-a-python-string) – user202729 Dec 23 '22 at 08:40

1 Answers1

2

repr returns the string representation of a string... which sounds redundant except that it double-escapes escape characters like you would if you typed them in yourself. It also encloses the string in quotes, but that can be easily removed.

>>> repr('\n\t\r')[1:-1]
'\\n\\t\\r'
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • 1
    With Python2, it will also escape/encode non-ascii characters (not sure if that is what the OP expected). – ekhumoro Feb 03 '16 at 17:13
  • @ekhumoro Yes, you are quite right. Thanks for pointing that out. – tdelaney Feb 03 '16 at 17:19
  • @ekhumoro In my case non-ascii characters aren't a concern, but it's good to know for the future. – ewok Feb 03 '16 at 17:20
  • This will escape actual backslashes too many times. – wim Nov 05 '20 at 19:56
  • @wim - I don't think so. If we had the single character `"\\"`, it would turn it into the two character `"\\\\"`. If you viewed it as a list `print(list(repr("\\"))[1:-1])` you'd get `['\\', '\\']`. – tdelaney Aug 05 '22 at 16:56
  • @tdelaney Hmm, can't exactly remember what I was thinking in that comment from 2 years ago, but expected behavior would be to _not_ escape the actual backslash (since it is not an escaped character in the original string). e.g. The result for input r'a\b' should just be `'a\\b'` again and not `'a\\\\b'` like this code gives. – wim Aug 05 '22 at 19:24
  • @wim - oops - should have checked more carefully. I got a comment notification plus a downvote for this answer... I assumed they were both for the same answer. Now I have to reply to the _real_ comment I skipped. – tdelaney Aug 05 '22 at 21:57