IT story

파이썬 문자열에서 3 개의 백 슬래시가 4와 같은 이유는 무엇입니까?

hot-time 2020. 9. 5. 10:34
반응형

파이썬 문자열에서 3 개의 백 슬래시가 4와 같은 이유는 무엇입니까?


'?\\\?'=='?\\\\?'주는지 말해 줄래 True? 그것은 나를 미치게 만들고 합리적인 대답을 찾을 수 없습니다 ...

>>> list('?\\\?')
['?', '\\', '\\', '?']
>>> list('?\\\\?')
['?', '\\', '\\', '?']

기본적으로 파이썬은 백 슬래시 처리에 약간 관대하기 때문입니다. https://docs.python.org/2.0/ref/strings.html 에서 인용 :

표준 C와 달리 인식되지 않는 모든 이스케이프 시퀀스는 문자열에 변경되지 않은 채 남아 있습니다. 즉, 백 슬래시는 문자열에 남아 있습니다.

(원본 강조)

따라서 파이썬에서는 세 개의 백 슬래시가 4와 같지 않습니다.는 인식 된 이스케이프 시퀀스가 ​​아니기 ?때문에 백 슬래시와 같은 문자를 따라 가면 두 문자가 함께 나오는 것 \?입니다.


조합이 유효한 이스케이프 시퀀스를 나타내는 경우 백 슬래시가 바로 뒤에 오는 문자에 대한 이스케이프 문자로 작동하기 때문입니다. 12 개 정도의 이스케이프 시퀀스가 여기나열됩니다 . 여기에는 개행 문자 \n, 가로 탭 \t, 캐리지 리턴 \r같은 명백한 문자 와 유니 코드 문자를 나타내는 \N{...}\N{WAVY DASH}들어 사용하는 명명 된 유니 코드 문자와 같은 더 모호한 문자가 포함 \u3030됩니다. 요점은 이스케이프 시퀀스가 ​​알려지지 않은 경우 문자 시퀀스가 ​​그대로 문자열에 남아 있다는 것입니다.

문제의 일부는 Python 인터프리터 출력이 사용자를 오도하는 것일 수도 있습니다. 이는 표시 될 때 백 슬래시가 이스케이프되기 때문입니다. 그러나 이러한 문자열 인쇄 하면 추가 백 슬래시가 사라집니다.

>>> '?\\\?'
'?\\\\?'
>>> print('?\\\?')
?\\?
>>> '?\\\?' == '?\\?'    # I don't know why you think this is True???
False
>>> '?\\\?' == r'?\\?'   # but if you use a raw string for '?\\?'
True
>>> '?\\\\?' == '?\\\?'  # this is the same string... see below
True

구체적인 예에서 첫 번째 경우 '?\\\?'첫 번째 \는 두 번째 백 슬래시를 이스케이프하고 단일 백 슬래시를 남기지 만 세 번째 백 슬래시는 \?유효한 이스케이프 시퀀스가 ​​아니기 때문에 백 슬래시로 남아 있습니다 . 따라서 결과 문자열은 ?\\?입니다.

두 번째 경우 '?\\\\?'첫 번째 백 슬래시는 두 번째를 이스케이프하고 세 번째 백 슬래시는 네 번째를 이스케이프하여 문자열이 ?\\?됩니다.

그래서 세 개의 백 슬래시가 네 개와 같은 것입니다.

>>> '?\\\?' == '?\\\\?'
True

3 개의 백 슬래시가있는 문자열을 만들려면 각 백 슬래시를 이스케이프 할 수 있습니다.

>>> '?\\\\\\?'
'?\\\\\\?'
>>> print('?\\\\\\?')
?\\\?

또는 "원시"문자열을 더 이해하기 쉽게 찾을 수 있습니다.

>>> r'?\\\?'
'?\\\\\\?'
>>> print(r'?\\\?')
?\\\?

이것은 문자열 리터럴에 대한 이스케이프 시퀀스 처리를 전환합니다. 자세한 내용은 문자열 리터럴 을 참조하십시오.


때문에 \x문자열에, 때 x와 같은 특별한 backslashable 문자 중 하나가 아닌 n, r, t, 0, 등, 다음 백 슬래시와의 문자열로 평가 x.

>>> '\?'
'\\?'

https://docs.python.org/2/reference/lexical_analysis.html의 문자열 리터럴 아래에있는 Python 어휘 분석 페이지에서

인식 된 모든 이스케이프 시퀀스를 나열하는 테이블이 있습니다.

\\는 === \ 인 이스케이프 시퀀스입니다.

\? 이스케이프 시퀀스가 ​​아니며 === \?

따라서 '\\\\'는 '\\'다음에 '\\'가 나오는 '\\'(둘은 이스케이프 된 \)입니다.

and '\\\' is '\\' followed by '\' which is also '\\' (one escaped \ and one raw \)

also, it should be noted that python does not distinguish between single and double quotes surrounding a string literal, unlike some other languages.

So 'String' and "String" are the exact same thing in python, they do not affect the interpretation of escape sequences.


mhawke's answer pretty much covers it, I just want to restate it in a more concise form and with minimal examples that illustrate this behaviour.

I guess one thing to add is that escape processing moves from left to right, so that \n first finds the backslash and then looks for a character to escape, then finds n and escapes it; \\n finds first backslash, finds second and escapes it, then finds n and sees it as a literal n; \? finds backslash and looks for a char to escape, finds ? which cannot be escaped, and so treats \ as a literal backslash.

As mhawke noted, the key here is that interactive interpreter escapes the backslash when displaying a string. I'm guessing the reason for that is to ensure that text strings copied from interpreter into code editor are valid python strings. However, in this case this allowance for convenience causes confusion.

>>> print('\?') # \? is not a valid escape code so backslash is left as-is
\?
>>> print('\\?') # \\ is a valid escape code, resulting in a single backslash
'\?'

>>> '\?' # same as first example except that interactive interpreter escapes the backslash
\\?
>>> '\\?' # same as second example, backslash is again escaped
\\?

참고URL : https://stackoverflow.com/questions/35121288/why-do-3-backslashes-equal-4-in-a-python-string

반응형