Reputation: 988
Ok,
I have two strings, "Hello\nWorld!"
and Hello\\nWorld!
. I have to compare those that way that \n
and \\n
equals.
Thats not hard. I just string1.replace("\n", "\\n")
.
But what if I have to do it right for all escape chars including unicode escapes, so manual replace is not an option.
UPDATE
Exaple case:
I read from file Hello\nWorld!
(as seen when file is opened in editor). Python will see Hello\\nWorld!
I want to compare the last one with first one the way they are equals.
Upvotes: 4
Views: 12339
Reputation: 369424
How about using unicode_escape
encoding?
>>> 'hello\r\n'.encode('unicode_escape') == 'hello\\r\\n'
True
>>> 'hello\r\n' == 'hello\\r\\n'.decode('unicode_escape')
True
In Python 3.x, you need to encode/decode the string/bytes:
>>> 'hello\r\n'.encode('unicode_escape').decode() == 'hello\\r\\n'
True
>>> 'hello\r\n' == 'hello\\r\\n'.encode().decode('unicode_escape')
True
Upvotes: 10