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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With