python - Why do backslashes appear twice? -
when create string containing backslashes, duplicated:
>>> my_string = "why\does\it\happen?" >>> my_string 'why\\does\\it\\happen?'
why?
what seeing representation of my_string
created __repr__()
method. if print it, can see you've got single backslashes, intended:
>>> print(my_string) why\does\it\happen?
you can standard representation of string (or other object) repr()
built-in function:
>>> print(repr(my_string)) 'why\\does\\it\\happen?'
python represents backslashes in strings \\
because backslash escape character - instance, \n
represents newline, , \t
represents tab.
this can trouble:
>>> print("this\text\is\not\what\it\seems") ext\is ot\what\it\seems
because of this, there needs way tell python really want 2 characters \n
rather newline, , escaping backslash itself, one:
>>> print("this\\text\is\what\you\\need") this\text\is\what\you\need
when python returns representation of string, plays safe, escaping backslashes (even if wouldn't otherwise part of escape sequence), , that's you're seeing. however, string contains single backslashes.
more information python's string literals can found at: string , bytes literals in python documentation.
Comments
Post a Comment