Python 中 SyntaxError: unterminated triple-quoted string literal 错误

Python“SyntaxError: unterminated triple-quoted string literal”发生在我们打开一个三引号字符串却忘记关闭它时。 要解决该错误,请确保关闭三引号字符串。

下面是一个产生上述错误的示例代码

# ⛔️ SyntaxError: unterminated triple-quoted string literal (detected at line 4)
example = """
  hello
  world

我们打开了一个三引号字符串但忘记关闭它,所以字符串永远不会结束。

要解决该错误,需要关闭三引号字符串。

example = """
  hello
  world
""" # 👈️ close string

#
# hello
# world
#
print(example)

上面示例中的三引号字符串使用双引号,但我们也可以使用单引号定义一个。

example = '''
  hello
  world
'''

#
# hello
# world
#
print(example)

我们只需确保保持一致,并使用用于标记其开始的相同三个引号关闭字符串。

三引号字符串与我们使用单引号或双引号声明的基本字符串非常相似。

但它们也使我们能够:

  • 在同一个字符串中使用单引号和双引号而不转义
  • 定义多行字符串而不添加换行符
example = '''
  It's Alice
  "hello"
'''

#
# It's Alice
# "hello"
#
print(example)

上面示例中的字符串同时使用了单引号和双引号,并且不必转义任何内容。

行尾自动包含在三引号字符串中,因此我们不必在末尾添加换行符。

如果我们只需要在字符串中使用单引号,那么使用双引号将字符串括起来会更容易。

example = "It's Alice"

# 👉️ "It's Alice"
print(example)

相反,如果我们的字符串包含双引号,只需将其用单引号括起来就不必转义任何内容。


总结

Python“SyntaxError: unterminated triple-quoted string literal”发生在我们打开一个三引号字符串却忘记关闭它时。 要解决该错误,请确保关闭三引号字符串。