为什么反斜杠出现两次? [英] Why do backslashes appear twice?
问题描述
当我创建一个包含反斜杠的字符串时,它们会被重复:
When I create a string containing backslashes, they get duplicated:
>>> my_string = "why\does\it\happen?"
>>> my_string
'why\\does\\it\\happen?'
为什么?
推荐答案
您所看到的是<$ c $的表示 c> my_string 由其 __ repr __()创建
方法。如果你打印它,你可以看到你实际上有单反斜杠,就像你打算一样:
What you are seeing is the representation of the my_string
created by its __repr__()
method. If you print it, you can see that you've actually got single backslashes, just as you intended:
>>> print(my_string)
why\does\it\happen?
您可以使用 repr()
内置函数:
You can get the standard representation of a string (or any other object) with the repr()
built-in function:
>>> print(repr(my_string))
'why\\does\\it\\happen?'
Python代表字符串中的反斜杠为 \\
,因为反斜杠是一个转义字符 - 例如 \\ n
表示换行符, \t
表示选项卡。
Python represents backslashes in strings as \\
because the backslash is an escape character - for instance, \n
represents a newline, and \t
represents a tab.
有时可能会让您陷入困境:
This can sometimes get you into trouble:
>>> print("this\text\is\not\what\it\seems")
this ext\is
ot\what\it\seems
正因为如此,需要一种方法来告诉Python你真的想要两个字符 \\\
,而不是一个换行符,你可以通过转义另一个来反转斜杠本身:
Because of this, there needs to be a way to tell Python you really want the two characters \n
rather than a newline, and you do that by escaping the backslash itself, with another one:
>>> print("this\\text\is\what\you\\need")
this\text\is\what\you\need
当Python返回一个字符串的表示形式时,它起着安全的作用,转义所有的反斜杠(即使它们不会成为零件)的转义序列),这就是你所看到的。但是,字符串本身只包含单个反斜杠。
When Python returns the representation of a string, it plays safe, escaping all backslashes (even if they wouldn't otherwise be part of an escape sequence), and that's what you're seeing. However, the string itself contains only single backslashes.
有关Python的字符串文字的更多信息,请参见:字符串和字节文字。
这篇关于为什么反斜杠出现两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!