In Python 3.x:
print(""s"") # SyntaxError
print("""s""") # prints s
print(""""s"""") # SyntaxError
print("""""s""""") # prints ""s
What is the reason behind this different behaviour, when there are different numbers of double quotes in the string?
In Python you can create multiline strings with """..."""
. Quoting the documentation for strings,
String literals can span multiple lines. One way is using triple-quotes:
"""..."""
or'''...'''
.
In your first case, ""s""
is parsed like this
"" (empty string literal) s "" (empty string literal)
Now, Python doesn't know what to do with s
. That is why it is failing with SyntaxError
.
In your third case, the string is parsed like this
""" "s """ (End of multiline string) `"`
Now the last "
has no matching "
. That is why it is failing.
In the last case, """""s"""""
is parsed like this
""" ""s """ ""
So, the multiline string is parsed successfully and then you have an empty string literal next to it. In Python, you can concatenate two string literals, by writing them next to each other, like this
print ("a" "b")
# ab
So, the last empty string literal is concatenated with the ""s
.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다