Skip to content

python: SyntaxError: EOL while scanning string literal โ€‹

This error message is indicating that there is a problem with a string in your code. Specifically, it is saying that the end of the line (EOL) was reached while the interpreter was still scanning the string, meaning that the string was not properly closed.

A common cause of this error is that the string is not properly enclosed in quotation marks. For example, the following code would produce the "EOL while scanning string literal" error:

EOL while scanning string literal in Python

python
my_string = "This is a string
print(my_string)

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

To fix this, you would need to add the closing quotation mark to properly end the string:

EOL while scanning string literal

python
my_string = "This is a string"
print(my_string)

Another cause is using mismatched quotation marks, such as starting a string with a double quote and ending it with a single quote.

EOL while scanning string literal in Python by mismatched quotes

python
my_string = "This is a string'
print(my_string)

To fix this, ensure the opening and closing quotes match:

EOL while scanning string literal fix in Python

python
my_string = "This is a string"
print(my_string)

Another cause is including a literal newline character directly inside a single-line string. To properly handle newlines, use the escape sequence \n or triple quotes for multi-line strings:

New line character usage in Python

python
# Using escape sequence
my_string = "This is a string\n"

# Using triple quotes for multi-line strings
my_string = """This is a string
that spans multiple lines"""

Hope it helps!

Do you find this helpful?

Dual-run preview โ€” compare with live Symfony routes.