Home > Blockchain >  python equal strings are not equal with new line character in it
python equal strings are not equal with new line character in it

Time:03-25

I have a password. It contains newline (lets for now omit why) character and is: "h2sdf\ndfGd" This password is in dict my_dict. When I just print values of dict I get "\" instead of "" - "h2sdf\ndfGd"! Don't understand why. When I get it and use it to authenticate to web server, it says that Authentication fails. When I try to compare:

my_dict["password"] == "h2sdf\ndfGd"

it returns False.

But when I try just print(my_dict["password"]) I get h2sdf\ndfGd which is identical, but for python it is not. Why? I am lost.

CodePudding user response:

Check this:

>>> print("h2sdf\ndfGd")
h2sdf
dfGd
>>> print("h2sdf\\ndfGd")
h2sdf\ndfGd

You simply have to escape \n with a double \ backslash, to prevent it to become a newline.

CodePudding user response:

Characters like tabs, newlines, which cannot be represented in a string are described using an escape sequence with a backslash.

In order to indicate that the backslash is not part of an escape sequence(\n, \t, ...), it must itself be escaped using another backslash: \\.

my_dict["password"] == "h2sdf\\ndfGd"

If you don't want to have to escape all your \, you can use a raw string instead.

Raw strings are prefixed with r or R, and treat backslashes \ as literal characters.

my_dict["password"] == r"h2sdf\ndfGd"
  • Related