Как мы знаем, такой язык программирования, как Python, является интерпретируемым языком, что, по сути, означает, что каждый блок или строка кода обрабатывается один за другим, а не полностью меняют всю программу на низкоуровневый код.
Всякий раз, когда интерпретатор Python просматривает строку кода и замечает что-то необычное, он вызывает ошибку, известную как синтаксическая ошибка. Как правило, ошибки возникают из-за отсутствия скобок, отсутствующих конечных кавычек и других фундаментальных аномалий в синтаксисе.
В данном руководстве мы рассмотрим одну из синтаксических ошибок, известную как EOL в Python, которая обычно возникает, когда мы пытаемся просканировать строковый литерал.
Мы должны эффективно понять значение EOL, прежде чем решать проблему. EOL – это сокращение от «End of Line». Ошибка EOL означает, что интерпретатор Python достиг конца строки при сканировании строкового литерала.
Строковые литералы, также известные как константы, должны быть заключены в одинарные или двойные кавычки. Достижение «конца строки» при попытке сканирования означает, что мы достигли последнего символа строки и не встретили конечные кавычки.
Давайте рассмотрим базовый пример, демонстрирующий, как возникает ошибка EOL.
Пример:
# defining a string value my_string = "This is my string literal, and it is broken... # printing the string value print("String:", my_string)
Выход:
File "D:Pythonternarypy.py", line 2 my_string = "This is my string literal, and it is broken... ^ SyntaxError: EOL while scanning string literal
Объяснение:
В приведенном выше фрагменте кода мы определили строковый литерал; однако мы пропустили кавычки в конце строки, что привело к синтаксической ошибке EOL при печати этой строки для пользователей.
В разделе вывода мы можем наблюдать маленькую стрелку, указывающую на последний символ строки, и демонстрирующую, что ошибка произошла, когда программа попыталась проанализировать этот сегмент оператора.
Теперь, когда мы поняли проблему, давайте разберемся в некоторых случаях, когда эта ошибка может появляться при выполнении кода Python.
«Syntax Error: EOL при сканировании строкового литерала» – как исправить
Мы можем столкнуться с этой ошибкой в четырех основных ситуациях при работе над программой Python. Эти четыре основные ситуации показаны ниже:
- Отсутствует конечная кавычка.
- Использование неправильной конечной кавычки.
- Строковая константа растягивается на несколько строк.
- Использование обратной косой черты перед конечной кавычкой.
Давайте начнем разбираться в каждой из этих ситуаций и постараемся их обойти.
Отсутствует конечная кавычка
Как обсуждалось в предыдущем фрагменте кода, интерпретатор Python выдает синтаксическую ошибку всякий раз, когда он достигает конца строкового литерала, и обнаруживает, что кавычка отсутствует.
Пример:
# defining a string value my_string = "This is my string literal, and it is broken... # printing the string value print("String:", my_string)
Объяснение:
Мы можем заметить, что кавычка в конце литеральной строки отсутствует, что также оправдывает синтаксическую ошибку. В каждом языке есть несколько основных правил синтаксиса, нарушение которых приводит к ошибкам.
Давайте теперь рассмотрим следующий синтаксис для решения вышеуказанной проблемы.
Решение:
# defining a string value my_string = "This is my string literal, and it is broken..." # printing the string value print("String:", my_string)
Выход:
String: This is my string literal, and it is broken...
Объяснение:
В приведенном выше фрагменте кода мы включили кавычки в конец литеральной строки. В результате строка успешно печатается для пользователей без каких-либо синтаксических ошибок.
Использование неправильной конечной кавычки
Мы можем использовать как “”, так и ” , чтобы заключить в Python определенную строковую константу. Однако программист часто использует неправильные кавычки в конце строкового значения. В такой ситуации программа выдает синтаксическую ошибку в терминах EOL.
Рассмотрим такую ситуацию на следующем примере:
Пример:
# defining a string value my_string = "This is my string literal with wrong quotation mark at the end.' # printing the string value print("String:", my_string)
Выход:
File "D:Pythonternarypy.py", line 2 my_string = "This is my string literal with wrong quotation mark at the end.' ^ SyntaxError: EOL while scanning string literal
Объяснение:
В приведенном выше фрагменте кода мы использовали неправильную кавычку в конце строкового значения, что привело к синтаксической ошибке.
Мы можем избежать такой проблемы, используя соответствующие кавычки в конце строки, как показано в следующем фрагменте кода.
Решение:
# defining a string value my_string = "This is my string literal with wrong quotation mark at the end." # printing the string value print("String:", my_string)
Выход:
String: This is my string literal with wrong quotation mark at the end.
Объяснение:
В приведенном выше фрагменте кода, как мы можем заметить, мы использовали совпадающую кавычку в конце строки, которая помогает нам избежать ошибки EOL.
Строковая константа растягивается на несколько строк
Есть разные начинающие программисты Python, которые делают ошибку, растягивая операторы более чем на одну строку. Python принимает во внимание новую строку как конец оператора, в отличие от других языков, таких как C ++ и Java, которые рассматривают ‘;’ как конец высказываний.
Давайте рассмотрим пример, демонстрирующий эту проблему.
Пример:
# defining a string value my_string = "This is my string literal... this is my new line" # printing the string value print("String:", my_string)
Выход:
File "D:Pythonternarypy.py", line 2 my_string = "This is my string literal... ^ SyntaxError: EOL while scanning string literal
Объяснение:
В приведенном выше фрагменте кода мы можем заметить, что код выглядит обычным; однако, как только начинается следующая строка, интерпретатор Python прекращает выполнение этого оператора, вызывая синтаксическую ошибку, не заключающую строковую константу.
Однако мы можем решить эту проблему, используя различные методы, как показано ниже:
Решение 1. Использование символа ‘ n’ для создания эффекта новой строки в строковой константе.
# defining a string value my_string = "This is my string literal...n this is my new line" # printing the string value print("String:", my_string)
Выход:
String: This is my string literal... this is my new line
Объяснение:
В приведенном выше фрагменте кода мы включили ‘ n’ в строковую константу, чтобы обеспечить эффект новой строки. В результате строковая константа разбивает оператор на несколько строк.
Теперь рассмотрим другое решение.
Решение 2. Использование тройных кавычек, ” ‘или “” “для хранения многострочных строковых констант.
# defining a string value my_string = """This is my string literal... this is my new line""" # printing the string value print("String:", my_string)
Выход:
String: This is my string literal... this is my new line
Объяснение:
В приведенном выше фрагменте кода мы использовали тройные кавычки “” “для хранения многострочных строковых констант.
Использование обратной косой черты перед конечной кавычкой
Обратная косая черта ‘’ отвечает за экранирование строки и вызывает синтаксическую ошибку.
Рассмотрим следующий пример:
# storing a directory path my_string = "D:PythonMy_Folder" # printing the string value print("String:", my_string)
Выход:
File "D:Pythonternarypy.py", line 2 my_string = "D:PythonMy_Folder" ^ SyntaxError: EOL while scanning string literal
Объяснение:
В приведенном выше фрагменте кода мы использовали обратную косую черту ‘’, чтобы отделить пути к папке друг от друга. Однако во время выполнения программы интерпретатор Python выдал синтаксическую ошибку.
Последняя обратная косая черта перед кавычкой экранирует строковую константу, и интерпретатор Python рассматривает “как одиночный символ. Эта escape-последовательность преобразуется в кавычки (“).
Мы можем решить эту проблему, используя следующий фрагмент кода.
Решение:
# storing a directory path my_string = "D:\Python\My_Folder\" # printing the string value print("String:", my_string)
Выход:
String: D:PythonMy_Folder
Объяснение:
В приведенном выше фрагменте кода мы использовали ‘\’ в строковой константе. В результате интерпретатор Python выполняет эту строку, не вызывая ошибки.
Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.
Ошибка переводится так: «(встретился) конец строки кода (EOL — end of line) при сканировании литерала строки». Такая ошибка обычно возникает, когда строка вообще не закрыта (нет закрывающей кавычки), например:
print('abc)
У вас эта ошибка происходит из-за того, обратные слеши в конце строк экранируют кавычку (делают кавычку частью строки, а не признаком ее конца). Чтобы это не происходило, нужно обратные слеши в конце строк удвоить (но убрать r, иначе в конце так и будет выводиться удвоенный обратный слеш):
print('/_/\')
print('>^,^<')
print(' / \')
print(' |_|)_/')
Или добавить пробелы после обратных слешей:
print(r'/_/ ')
print(r'>^,^<')
print(r' / ')
print(r' |_|)_/')
В строках добавил еще начальные пробелы, чтобы голова котика не была смещена.
Python is widely used by many developers all around the world to create mind-blowing applications. What’s more exciting about Python is that it’s dynamically programmed. That means you don’t have to declare variable types when constructing a variable. It’s automatically selected. On top of that, error handling allows you to catch and handle multiple errors of the same type. Incomplete parenthesis, brackets, and quotes all throw different types of errors. EOL While Scanning String Literal Error is one of the errors while parsing strings in Python.
EOL While Scanning String Literal Error appears when your python code ends before ending the string quotes. In simpler terms, your string quotes are missing in the code either by human mistake or incorrect syntax mistake. As Python falls under interpreted language (which means your code is executed line by line without compiling), all the statements before the EOL errors are executed properly.
In this post, we’ll have a look at all the causes and solutions of this error. Moreover, some bonus FAQs to avoid EOL errors in the future.
What exactly is EOL While Scanning String Literal?

Without a complete grasp of a problem, it’s very difficult to debug it. In layman’s terms, EOL stands for “End Of the Line”. It means that your codes ended without completing a certain syntax end. For example, when you declare a string in Python, quotes (“) are used. At this time, if you don’t end the line with another quote (“), it’ll throw EOL While Scanning Error in the SyntaxError category.
EOL is triggered when your python interpreter has completed reading the last character of your code. In simpler words, it’s called when the file ends. Upon calling the EOL, the interpreter checks if there are incomplete string quotes, brackets, and curly brackets. If yes, then the SyntaxError is thrown.
If you are a beginner, you’ll have a hard time understanding what is string literal. The following section will help you to understand it.
What is String Literal in Python?
String literal is a set of characters enclosed between quotation marks (“). All the characters are noted as a sequence. In Python, you can declare string literals using three types, single quotation marks (‘ ‘), double quotation marks (” “), and triple quotation marks (“”” “””). Strings are arrays and their characters can be accessed by using square brackets. The following example will help you to understand String Literals.
String Literal Example
example1 = 'Single Quotes String' example2 = "Double Quotes String" example3 = """Triple Quotes String""" print(example1[0]) # will print S
There are known causes for the EOL error in Python. Once you know all of them, you can easily debug your code and fix it. Although, these causes are not necessarily the only known causes for the error. Some other errors might also result in throwing EOL error. Let’s jump right into all the causes –
Cause 1: Unclosed Single Quotes
String Literals in python can be declared by using single quotes in your program. These literals need to be closed within two single quotes sign (‘ ‘). If you failed to enclose the string between these two quotes, it’ll throw EOL While Scanning String Literal Error. Moreover, if you give an extra single quote in your string it’ll also throw the same error. Following examples will help you to understand –
Example 1 –
example1 = 'Single Quotes String example2 = "Double Quotes String" example3 = """Triple Quotes String""" example1[0] # will print S
In this example, there is a missing end single quote in line 1. This missing quote causes the interpreter to parse the next lines as strings that are incorrect. Adding a single quote at the end of line 1 can fix this problem.
Example 2 –
x = 'This is a String print(x)
In this example, there is a missing single quote at the end of line 1.
Example 3 –
x = 'It's awesome' print(x)
In this special example, there three single quotes in the first line. According to python, the string for x variable ends at the send single quote. The next part will be treated as a part of another code, not a string. This causes SyntaxError to appear on your screen.
Cause 2: Unclosed Double Quotes
String Literals can also be declared by using double-quotes. In most of hte programming languages, double quotes are the default way to declare a string. So, if you fail to enclose the string with double quotes it’ll throw SyntaxError. Moreover, if you’ve used an odd number of quotes (“) in your string, it’ll also throw this error because of the missing quote. The following example will help you to understand –
Example 1 –
example1 = 'Single Quotes String' example2 = "Double Quotes String example3 = """Triple Quotes String""" example1[0] # will print S
In this example, there is a missing double quote at the end of the second line. This missing quote causes the interpreter to parse all the following codes as part of the string for variable example2. In the end, it throws an EOL error when it reaches the end of the file.
Example 2 –
x = "This is a String print(x)
Similarly, there is a missing double quote at the end of line 1.
Example 3 –
x = "It"s awesome" print(x)
In this special example, there three double quotes in the first line. According to python, the string for x variable ends at the send single quote. The next part will be treated as a part of another code, not a string. This causes SyntaxError to appear on your screen.
Cause 3: Unclosed Triple Quotes
In Python, there is a special way of declaring strings using three double quotes (“””). This way is used when you have to include double quotes and single quotes in your string. With this type of declaration, you can include any character in the string. So, if you did not close this triple quotes, I’ll throw an EOL error. Following examples will help you to understand –
Example 1 –
In line 3 of the example, there is a missing quote from the set of triple quotes. As a result, the python interpreter will treat all the following lines as a part of the string for example3 variable. In the end, as there are no ending triple quotes, it’ll throw EOL error.
example1 = 'Single Quotes String' example2 = "Double Quotes String" example3 = """Triple Quotes String"" example1[0] # will print S
Example 2 –
Similar to example 1, two of the quotes are missing from line 1.
x = """This is a String" print(x)
Cause 4: Odd Number of Backslashes in Raw String
Backslashes are used in the string to include special characters in the string. For example, if you want to add double quotes in a doubly quoted string, you can use ” to add it. Every character after backslashes has a different meaning for python. So, if you fail to provide a corresponding following character after the backslash (), you’ll get EOL While Scanning String Literal Error. Following examples will help you understand it –
Example 1 –
The following string is invalid because there is no following character after the backslash. Currently, python processes the strings in the same way as Standard C. To avoid this error put “r” or “R” before your string.
Example 2 –
The following example contains an odd number of backslashes without the following characters. This causes the EOL error to raise as the interpretation expects the next character.
Example 3 –
The last backslash in the string doesn’t have the following character. This causes the compiler to throw an error.
How do you fix EOL While Scanning String Literal Error?
Since the causes of the errors are clear, we can move on to the solution for each of these errors. Although each cause has a different way of solving it, all of them belong to string literals. All of these errors are based on incomplete string literals which are not closed till the end. Following solutions will help you to solve each of these errors –
Solution for Single Quoted Strings
Fixing incomplete quoted strings is an easy task in Python. Firstly, look for the string declarations in your code. After finding it, check if the string has incomplete end single quotes (‘). Also, check if the string has any extra single quotes. After locating the string, add a single quote at the end of the string.
Example 1 –
example1 = 'Single Quotes String' # added single quote here example2 = "Double Quotes String" example3 = """Triple Quotes String""" example1[0] # will print S

Solution for double quoted Strings in EOL While Scanning String Literal
Similarly, for double quotes, check if any of the string declarations in your code have missing double quotes (“). If not, check for an additional double quote inside the string. You can use the Find option in your IDE to find it quickly. Locate this error and fix it by adding an extra double quote at the end of this line.
Example –
example1 = 'Single Quotes String' example2 = "Double Quotes String" # added double quote here example3 = """Triple Quotes String""" example1[0] # will print S

Solution for incomplete backslashes in Strings
Firstly, check if your codes contains and backslashes. If yes, move to the specific line and check if it’s included inside the string. Currently, the backslashes allow us to add special characters in the string. If your string contains such backslashes, remove them and try to run the code. Additionally, if you want to add special characters, you can use the tripe quoted strings as well. Following examples can help you to understand it properly –
# invalid x = "" x = "\" x = "\"" # valid x = "\" x = "\\" x = "\""

To add special characters in the string, you can use backslashes in the string. For example, t adds a new tab space, n adds a new line, \ adds a literal backslash, and many others. Make sure that you use them carefully to avoid any EOF While Scanning Errors.
EOL While Scanning Triple Quoted String Literal Error
Triple Quoted Strings are a powerful way of defining strings in Python. It can be used if you want to add characters like double quotes, single quotes, and other special characters in the string. Multiline Line String Literals can also be declared by using Tripe Quoted Strings. Also, the documentation of codes is done via triple quotes in python. Many times, we mistakenly use less than three quotes to initialize it. In such cases, EOL while scanning triple quoted string literal error appears.
The basic syntax of triple quoted string is –
x = """This is a triple quoted string""""
Using the above method, you can declare strings in triple quotes. Check – How to Remove Quotes From a String in Python
Coming back to our error, whenever a user uses less than 6 quotes (3 at front and 3 at the end), the interpreter throws an EOL SyntaxError. To fix this, make sure that you keep the proper 3 + 3 quotes structure in your code as shown above. Follow this example to get an idea –
# invalid x = """Incorrect String"" x = ""Incorrect String""" x = "Incorrect String""" x = """Incorrect String" x = """Incorrect "String"" # valid x = """Correct String""" x = """Correct "String""" x = """Correct ""String"""
Note – You can add any number of single and double quotes inside the string but the three quotes on start and end are mandatory.
How to fix SyntaxError unexpected EOF while parsing?
As EOL While Scanning String Literal Error occurs due to incomplete strings, unexpected EOF while parsing occurs when there are other incomplete blocks in the code. The interpreter was waiting for certain brackets to be completed but they never did in the code. The main cause of this error is incomplete brackets, square brackets, and no indented blocks.
For example consider a, “for” loop in your code that has no intended block following it. In such cases, the Syntax Error EOF will be generated.
Moreover, check the parameters passed in your functions to avoid getting this error. Passing an invalid argument can also result in this error. Following code, an example can help you to understand the parsing errors –
Example 1 –
In this example, there is a bracket missing from the print() statement. The interpreter reaches the End of the Line before the bracket completes, resulting in SyntaxError. Such errors can be solved by simply adding another bracket.
Error –
x = "Python Pool is awesome" print(x.upper() # 1 bracket is missing
Solution –
x = "Python Pool is awesome" print(x.upper())
Example 2 –
In this example, there is no code block after the “for” statement. The python interpreter expects an indented code block after the for a statement to execute it, but here it’s not present. As a result, this code throws an EOF error. To solve this error, insert an intended block at the end.
Error –
Solution –
x = 5 for i in range(5): print(x)
Common FAQs
Following are some of the common FAQs related to this topic –
How to use n in Python?
n refers to a new line in programming languages. To use it in python, you need to declare a string by using double quotes (“) and then add a “n” inside it to create a new line. Following is an example for it –
x = "First linenSecond Line" print(x)
Output –
First line
Second Line
How to Use Backslash in Python?
Backslashes are a great way to add special characters to your string. It is used to add quotes, slashes, new lines, tab space, and other characters in the string. To use it, you first need to declare a string using double quotes and then use “” to add characters.
x = "This adds a tab spacetbetween" print(x)
Output –
This adds a tab space between
Which form of string literal ignores backslashes?
Only raw strings literals ignore the backslashes in the Python code. To declare a raw string, you have to mention an “r” or “R” before your string. This helps to understand the python interpreter to avoid escape sequences,
x = r'pythonpool' print(x)
Output –
pythonpool
Must Read
Python getopt Module: A – Z Guide
4 Ways to Draw a Rectangle in Matplotlib
5 Ways to Check if the NumPy Array is Empty
7 Powerful ways to Convert string to list in Python
Final Words: EOL While Scanning String Literal
Strings have helpful in thousands of ways in Python. As using them can provide easy access to a sequence of characters and their attributes. The only problem is that you have to take care of their syntax. Any invalid syntax and invalid backslashes in the string can cause EOF errors to appear. To avoid this error, follow all the steps from the post above.
Happy Coding!
Python is an interpreted language, which essentially means that each line of code is executed one by one, rather than converting the entire program to a lower level code at once.
When the Python interpreter scans each line of code and finds something out of ordinary, it raises an error called the Syntax Error. These errors can be raised by “a missing bracket”, “a missing ending quote” and other basic anomalies in the syntax.
The Syntax Error we are going to discuss in this article is “EOL while scanning string literal”.
What does this error mean?
We can not solve a problem unless we effectively understand it. EOL stands for “End of Line”. The error means that the Python Interpreter reached the end of the line when it tried to scan the string literal.
The string literals (constants) must be enclosed in single and double quotation marks. Reaching the “end of line” while scanning refers to reaching the last character of the string and not encountering the ending quotation marks.
# String value s = "This is a string literal... # Printing the string print(s)
Running the above code gives the following output:
File "EOL.py", line 2 s = "This is a string literal... ^ SyntaxError: EOL while scanning string literal
The small arrow points the last character of the string indicating that the error occurred while parsing that component of the statement.
Now that we understand the problem, let us look at some instances where it can appear while running python code.
There can be four main situations where this error can be encountered:
Missing the ending quotation mark
As explained in the above code snippet, Python interpreter raises a syntax error when it reaches the end of the string literal and finds that quotation mark is missing.
# Situation #1 # Missing the ending quotation mark s = "This is a string literal... # Printing the string print(s)
The reason of this syntax error is quite obvious. Every language has some basic syntax rules, which when violated lead to errors.
Solution:
The trivial solution is to respect the syntax rule and place the ending quotation marks.
# Solution #1 # Place the ending quotation mark s = "This is a string literal..." # Printing the string print(s)
Using the incorrect ending quotation mark
Python allows the use of ' '
and " "
for enclosing string constants. Sometimes programmers use the incorrect quotation counterpart for ending the string value.
# Situation #2 # Incorrect ending quotation mark s = "This is a string literal...' # Printing the string print(s)
Even though the string appears to be enclosed, it is not the case. The Python interpreter searches for the matching quotation mark at the ending of the string.
Solution:
The basic solution is to match the beginning and the ending quotation marks.
# Solution #2 # Match the quotation marks s = "This is a string literal..." # Printing the string print(s)
String constant stretching to multiple lines
Many novice Python programmers make the mistake of stretching statements to multiple lines. Python considers a new line as the end of the statement, unlike C++ and Java that consider ';'
as the end of statements.
# Situation #3 # String extending to multiple lines s = "This is a string literal... Going to the next line" # Printing the string print(s)
At first, the code may seem ordinary, but as soon as the new line is started, the Python interpreter puts an end to that statement and raises an error for not enclosing the string constant.
Solution 1:
The escape sequence 'n'
can be used to provide the effect of a new line to the string constant. Visit here to learn about other escape sequences.
# Solution #3.1 # Using the escape sequences n -> Newline s = "This is a string literal... n Going to the next line" # Printing the string print(s)
Solution 2:
The other solution is to use triple quotation marks, '''
or """
for storing multi-line string literals.
# Solution #3.2 # Using triple quotation marks s = """This is a string literal... Going to the next line""" # Printing the string print(s)
Using backslash before the ending quotation mark
The backslash ''
is responsible for escaping the string and causing syntax error.
# Situation #4 # Storing a directory path s = "homeUserDesktop" # Printing the string print(s)
The last backslash before the quotation mark escapes the string constant and Python interpreter considers "
as a single character. This escape sequence translates to a quotation mark (")
.
Solution:
The solution is to replace the backslash with an escape sequence for a backslash (\)
.
# Solution #4 # Storing a directory path s = "\home\User\Desktop\" # Printing the string print(s)
Conclusion
A single error in a code spanning to a thousand lines can cost hours to debug. Therefore it is advised to write such codes with extreme concentration and using the correct syntax.
We hope this article was fruitful in solving the reader’s errors. Thank you for reading.
In this tutorial, you’ll learn how to fix one of the most common Python errors: SyntaxError – EOL while scanning string literal. There are three main causes for this error and this tutorial will help you resolve each of these causes. SyntaxErrors are indicative of errors with your code’s syntax. Since your code’s syntax is critically important in how Python interprets your code, knowing how to resolve these types of issues is very important for a Pythonista of any skill level.
By the end of this tutorial, you’ll have learned:
- What the
SyntaxError
means - What the 3 main causes of the error are and how to resolve them
To fix the Python SyntaxError: EOL while scanning string literal, you can use any of the following methods:
- Close strings that have a missing quotation mark
If your strings are missing quotation marks at the end, add the matching quotation character.
- Use triple quotes for strings that span multiple lines
If your string spans multiple lines, ensure that you are wrapping your strings in triple quotes.
- Escape strings that span multiple lines with the character
If you don’t want to use triple quotes for multi-line strings, be sure to escape each line break with a character.
- Ensure that strings use matching quotation marks
If your strings are using mismatching quotation marks, be sure to correct them to matching ones.
Understanding Python SyntaxError: EOL while scanning string literal
What is a SyntaxError in Python?
A Python SyntaxError is raised when the Python interpreter runs into code with syntax that is invalid. For example, if code rules such as closing quotes aren’t followed, Python raises a SyntaxError.
Because syntax errors refer to issues by how your code is written, specifically, fixing these issues relates to fixing the syntax of your code. Thankfully, the traceback that Python returns about the error identifies where the issue can be found.
Specifically, the Python SyntaxError: EOL while scanning string literal refers to strings ending improperly at the end of the line of code. This can point to three roots causes, that we’ll explore in this tutorial!
Now that you have a strong understanding of what this error refers to, let’s identify three of the main causes of this error.
Missing Quotes Causing Python SyntaxError
The most common cause of the Python SyntaxError: EOL while scanning string literal is due to missing quotes at the end of a string. This refers to a string being opened by using either '
, "
, or """
and not closing the string properly.
Let’s see what this looks like in Python code:
# Raising a SyntaxError When a String Isn't Closed
text = 'Welcome to datagy.io
# Raises:
# Input In [1]
# text = 'Welcome to datagy.io
# ^
# SyntaxError: EOL while scanning string literal
The trackback error indicates the line on which the error is happening and where the quote is expected. We can see the arrow points to where the string is expected to be ended.
Beginning in Python 3.10, this error message will become much clearer. In fact, it will raise a different SyntaxError, indicating which string literal hasn’t been closed properly. Let’s see what this looks like in Python 3.10+:
# New SyntaxError in Python 3.10
text = 'Welcome to datagy.io
# Raises
# File "", line 1
# text = 'Welcome to datagy.io
# ^
# SyntaxError: unterminated string literal (detected at line 1)
In order to resolve this issue, we simply need to close the string with a corresponding quote character. Let’s fix this error and run our code without issue:
# Resolving a SyntaxError When Strings Aren't Closed
text = 'Welcome to datagy.io'
In the following section, you’ll learn how to fix a Python SyntaxError caused by strings spanning multiple lines.
Strings Spanning Multiple Lines Causing Python SyntaxError
Another cause of the Python SyntaxError: EOL while scanning string literal error is strings spanning multiple lines. Python allows you to create multi-line strings. However, these strings need to be created with triple quotation marks, using either '''
or """
.
The following code will raise a Python SyntaxError:
# Raising a Python SyntaxError When Spanning Multiple Lines
text = 'Welcome to
datagy.io'
# Raises:
# Input In [3]
# text = 'Welcome to
# ^
# SyntaxError: EOL while scanning string literal
We can see that the error raised indicates where Python expected a string to be ended. However, in this case it’s not as clear that the string actually spans multiple lines.
We can resolve this type of Python SyntaxError using two methods:
- We can wrap our string in triple quotes, or
- Escape our line breaks
Resolve Strings Spanning Multiple Lines with Triple Quotes
In order to resolve this error, the string simply needs to be created with a set of triple quotes. This ensures that Python can correctly identify that the string should span multiple lines. Let’s see how we can resolve this error:
# Resolving a Python SyntaxError With Triple Quotes
text = """Welcome to
datagy.io"""
By using triple-quotes on a string, Python allows your strings to span multiple lines. Similarly, you could use single triple quotes like '''
.
Another method to resolve this is to simply escape the line breaks.
Resolve Strings Spanning Multiple Lines with Line Escaping
Python also allows you to escape line breaks by using the \
character. This lets Python know that the line break is aesthetic and should be ignored. Let’s see how we can resolve our Python SyntaxError using the escape character.
# Resolving a Python SyntaxError With Line Escaping
text = 'Welcome to
datagy.io'
We can see that this allows the interpreter to properly read the multi-line string. In the following section, you’ll learn how to resolve the third cause of the Python SyntaxError.
Mismatched Quotes Causing Python SyntaxError
The final cause of the Python SyntaxError: EOL while scanning string literal is using mismatched quotation marks. This error occurs when the code uses quotes that aren’t the same style. Because Python allows you to use either '
or "
, ensuring that they are used consistently is important.
Let’s see what this error may look like:
# Raising a SyntaxError When Using Mismatched Quotes
text = "Welcome to datagy.io'
# Raises:
# Input In [6]
# text = "Welcome to datagy.io'
# ^
# SyntaxError: EOL while scanning string literal
Python indicates that the string isn’t properly closed. It indicates that there should be a supporting quote at the end of the string, following the '
character. We can resolve this error by simply using a matching "
character:
# Resolving a Python SyntaxError Caused by Mismatched Quotes
text = "Welcome to datagy.io"
We can see that by using the same type of quote the error is resolved.
Conclusion
In this guide, you learned how to resolve the Python SyntaxError: EOL while scanning string literal. This error has three main causes which were explored throughout. First, you learned how to resolve the error caused by missing quotes. Then, you learned how to resolve the error caused by strings spanning multiple lines. Finally, you learned how to resolve the error caused by mismatched quotes.
Additional Resources
To learn more about related topics, check out the guides below:
- How to Fix: Python indentationerror: unindent does not match any outer indentation level Solution
- Python: Remove Special Characters from a String
- Python: Remove Newline Character from String
- Python Strings: Official Documentation