Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python compare "\n" escape chars with "\\n"

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.

like image 547
Hannes Karppila Avatar asked May 10 '26 01:05

Hannes Karppila


1 Answers

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
like image 59
falsetru Avatar answered May 11 '26 13:05

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!