Python syntaxerror unexpected character after line continuation character

How to Solve Python SyntaxError: unexpected character after line continuation character

In Python, we can use the backslash character \ to break a single line statement into multiple lines to make it easier to read. If we want to use this continuation character, it must be the last character of that line. The Python interpreter will raise “SyntaxError: unexpected character after line continuation character” if another character follows it. This tutorial will detail the error definition, examples of scenarios that cause the error, and how to solve it.

Table of contents

SyntaxError: unexpected character after line continuation character

SyntaxError tells us that we broke one of the syntax rules to follow when writing a Python program. If we violate any Python syntax, the Python interpreter will raise a SyntaxError. Another example of a SyntaxError is abruptly ending a program before executing all of the code, which raises “SyntaxError: unexpected EOF while parsing“.

Читайте также:  Python dictionary to javascript

The part “unexpected character after line continuation character” tells us that we have some code after the line continuation character \ . We can use the line continuation character to break up single line statements across multiple lines of code. Let’s look at the example of writing part of the opening sentence of A Tale of Two Cities by Charles Dickens:

long_string = "It was the best of times, it was the worst of times,"\ "it was the age of wisdom, it was the age of foolishness,"\ "it was the epoch of belief, it was the epoch of incredulity,"\ "it was the season of Light, it was the season of Darkness. " print(long_string)

In this example, we break the string into three lines, making it easier to read. If we print the string, we will get a single string with no breaks.

It was the best of times, it was the worst of times,it was the age of wisdom, it was the age of foolishness,it was the epoch of belief, it was the epoch of incredulity,it was the season of Light, it was the season of Darkness. 

Three examples scenarios could raise this SyntaxError

  • Putting a character after the line continuation character
  • Division using the line continuation character
  • Incorrect use of the new line character \n

Let’s go through each of these mistakes and present their solutions.

Example #1: Putting a Character after the line continuation character

If we put any character after the line continuation character, we will raise the SyntaxError: unexpected character after line continuation character. Let’s put a comma after the first break in the long string above:

long_string = "It was the best of times, it was the worst of times,"\, "it was the age of wisdom, it was the age of foolishness,"\ "it was the epoch of belief, it was the epoch of incredulity,"\ "it was the season of Light, it was the season of Darkness. " print(long_string) 
 long_string = "It was the best of times, it was the worst of times,"\, ^ SyntaxError: unexpected character after line continuation character

Solution

To solve this, we need to ensure there are no characters after the line continuation character. We remove the comma after the first line continuation character in this example.

Читайте также:  Java load class jar file

Example #2: Division using the Line Continuation Character

In this example, we will write a program that calculates the speed of a runner in miles per hour (mph). The first part of the program asks the user to input the distance they ran and how long it took to run:

distance = float(input("How far did you run in miles?")) time = float(input("How long did it take to run this distance in hours?"))

We use the float() function to convert the string type value returned by input() to floating-point numbers. We do the conversion to perform mathematical operations with the values.

Next, we will try to calculate the speed of the runner, which is distance divided by time:

running_speed = distance \ time print(f'Your speed is: mph')

We use the round() function to round the speed to one decimal place. Let’s see what happens when we try to run this code:

How far did you run in miles?5 How long did it take to run this distance in hours?0.85 running_speed = distance \ time ^ SyntaxError: unexpected character after line continuation character

We raise the SyntaxError because we tried to use \ as the division operator instead of the / character.

Solution

To solve this error, we use the division operator in our code

running_speed = distance / time print(f'Your speed is: mph')

We have successfully calculated the speed of the runner!

Example #3: Incorrect Use of the New Line Character “\n”

In this example scenario, we will write a program that writes a list of runner names and speeds in miles per hour to a text file. Let’s define a list of runners with their speeds:

runners = [ "John Ron: 5.9 mph", "Carol Barrel: 7.9 mph", "Steve Leaves: 6.2 mph" ]
with open("runners.txt", "w+") as runner_file: for runner in runners: runner_file.write(runner + \n)
 runner_file.write(runner + \n) ^ SyntaxError: unexpected character after line continuation character

The code loops over the runner details in the list and writes each runner to the file followed by a newline character in Python, “ \n “. The newline character ensures each runner detail is on a new line. If we try to run the code, we will raise the SyntaxError:

 runner_file.write(runner + \n) ^ SyntaxError: unexpected character after line continuation character

We raised the error because we did not enclose the newline character in quotation marks.

Solution

If we do not enclose the newline character in quotation marks, the Python interpreter treats the \ as a line continuation character. To solve the error, we need to enclose the newline character in quotation marks.

with open("runners.txt", "w+") as runner_file: for runner in runners: runner_file.write(runner + "\n")

If we run this code, it will write a new file called runners.txt with the following contents:

John Ron: 5.9 mph Carol Barrel: 7.9 mph Steve Leaves: 6.2 mph

Summary

Congratulations on reading to the end of this tutorial. The SyntaxError: unexpected character after line continuation character occurs when you add code after a line continuation character. You can solve this error by deleting any characters after the line continuation character if you encounter this error. If you are trying to divide numbers, ensure you use the correct division operator (a forward slash). If you are using any special characters that contain a backslash, like a newline character, ensure you enclose them with quotation marks.

To learn more about Python for data science and machine learning, go to the online courses pages on Python for the best courses online!

Have fun and happy researching!

Share this:

Источник

Почему возникает данная ошибка при запуске любого скрипта питон?

SyntaxError: unexpected character after line continuation character
Получаю данную ошибку при запуске любого файла питон, в чем может быть причина?!

Простой 10 комментариев

boypush

boypush

boypush

Михаил, python not found. я пытаюсь запускать из под оболочки linux, я так понимаю данная ошибка вызвана путями, то есть когда я переношу с рабочего стола в терминал то путь неправильно указывается, слеши или чтото еще.

boypush

Сергей Горностаев, SyntaxError: unexpected character after line continuation character
Но уже не актуально)

boypush

60da513040d50107284686.png

Сергей Горностаев,
такая была ошибка, но уже не актуально.

Vindicar

SyntaxError: unexpected character after line continuation character

У тебя в строке где-то болтается символ \ вне строковой константы.
Знак деления не перепутал, случаем?

Vindicar вам правильно посоветовал. И еще могу посоветовать проверить кодировку используемую в написании. Желательно сменить на UTF-8, если отличная от нее.

Антон,
Судя по ошибке похоже запускаете так:
В консоли прописываете python3, жмете Enter, запускается интерпретатор питона, при этом еще стоит символ
>>>
И вот туда уже вставляете свой путь к скрипту и пытаетесь запустить
d:\python\my_script.py
Естественно он будет ругаться, т.к. в интерпретаторе хочет видеть команды языка, а не подобные строки.

Для запуска надо было в консоли системы сразу писать путь к скрипту
python3 d:\python\my_script.py

Источник

SyntaxError: unexpected character after line continuation character

In Python, SyntaxError: unexpected character after line continuation character occurs when you misplace the escape character \ inside a string or characters that split into multiline.

The backslash character «\» is used to indicate the line continuation in Python. If any characters are found after the escape character, the Python interpreter will throw SyntaxError: unexpected character after line continuation character.

SyntaxError: unexpected character after line continuation character.

Sometimes, there are very long strings or lines, and having that in a single line makes code unreadable to developers. Hence, the line continuation character «\» is used in Python to break up the code into multiline, thus enhancing the readability of the code.

Example of using line continuity character in Python

message = "This is really a long sentence " \ "and it needs to be split acorss mutliple lines " \ "to enhance readibility of the code" print(message) # Output This is really a long sentence and it needs to be split acorss mutliple lines to enhance readibility of the code

As you can see from the above example, it becomes easier to read the sentence when we split it into three lines.

Fixing unexpected character after line continuation character

Let’s take a look at the scenarios where this error occurs in Python.

  1. Using backslash as division operator in Python
  2. Adding any character right after the escape character
  3. Adding new line character in a string without enclosing inside the parenthesis

Using backslash as division operator in Python

Generally, new developers tend to make a lot of mistakes, and once such is using a backslash \ as a division operator, which throws Syntax Error.

# Simple division using incorrect division operator a= 10 b=5 c= a\b print(c) # Output File "c:\Projects\Tryouts\listindexerror.py", line 11 c= a\b ^ SyntaxError: unexpected character after line continuation character

The fix is pretty straightforward. Instead of using the backslash \ replace it with forward slash operator / as shown in the below code.

# Simple division using correct division operator a= 10 b=5 c= a/b print(c) # Output 2 

Adding any character right after the escape character

In the case of line continuity, we escape with \ and if you add any character after the escaper character Python will throw a Syntax error.

message = "This is line one \n" \+ "This is line two" \ "This is line three" print(message) # Output File "c:\Projects\Tryouts\listindexerror.py", line 1 message = "This is line one \n" \+ ^ SyntaxError: unexpected character after line continuation character

To fix this, ensure you do not add any character right after the escape character.

message = "This is line one \n" \ "This is line two \n" \ "This is line three" print(message) # Output This is line one This is line two This is line three

Adding any character right after the escape character

If you are using a new line character while printing or writing a text into a file, make sure that it is enclosed with the quotation «\n» . If you append \n , Python will treat it as an escape character and throws a syntax error.

fruits = ["Apple","orange","Pineapple"] for i in fruits: print(i+\n) # Output File "c:\Projects\Tryouts\listindexerror.py", line 3 print(i+\n) ^ SyntaxError: unexpected character after line continuation character

To fix the issue, we have replaced \n with «\n» enclosed in the quotation marks properly.

fruits = ["Apple","orange","Pineapple"] for i in fruits: print(i+"\n")

Источник

Оцените статью