Reputation: 21443
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.
Upvotes: 0
Views: 900
Reputation: 77337
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'
Upvotes: 2