SyntaxError: unterminated triple-quoted string literal


Borislav Hadzhiev

Mon Apr 25 20222 min read

SyntaxError: unterminated triple-quoted string literal #

The Python "SyntaxError: unterminated triple-quoted string literal" occurs when we open a triple-quoted string and forget to close it. To solve the error, make sure to close the triple-quoted string.

syntaxerror unterminated tripple quoted string literal

Here is an example of how the error occurs.
# ⛔️ SyntaxError: unterminated triple-quoted string literal (detected at line 4) example = """ hello world

We opened a triple-quoted string but forgot to close it, so the string never ends.

To solve the error, close the triple-quoted string.
example = """ hello world """ # 👈️ close string # # hello # world # print(example)

The triple-quoted string in the example above uses double quotes, but you can also define one using single quotes.
example = ''' hello world ''' # # hello # world # print(example)
You just have to make sure to be consistent and close the string with the same three quotes that were used to mark its start.

Triple-quotes strings are very similar to basic strings that we declare using single or double quotes.

But they also enable us to:

  • use single and double quotes in the same string without escaping
  • define a multi-line string without adding newline characters
example = ''' It's Alice "hello" ''' # # It's Alice # "hello" # print(example)

The string in the example above uses both single and double quotes and doesn't have to escape anything.

End of lines are automatically included in triple-quoted strings, so we don't have to add a newline character at the end.

If you only have to use a single quote in the string, it would be easier to just wrap the string using double quotes.
example = "It's Alice" # 👉️ "It's Alice" print(example)

Conversely, if your string contains double quotes, just wrap it in single quotes to not have to escape anything.

Use the search field on my Home Page to filter through my more than 1,000 articles.