SyntaxError: unterminated triple-quoted string literal

avatar

Borislav Hadzhiev

Last updated: Apr 25, 2022

banner

Photo from Unsplash

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.

main.py
# ⛔️ 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.

main.py
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.

main.py
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 multiline string without adding newline characters
main.py
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.

main.py
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.

Conclusion #

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.