Только сегодня поставил Питон и приступил к изучению. Написал в IDLE:
>>>print("hello world")
IDLE вернул, все супер. Сохранил в hw.py, интерпретатор не запускает файл и ругается вот так вот
«SyntaxError: unexpected character after line continuation character»
Что он хочет от меня?
задан 2 авг 2018 в 14:00
Стефан ВорониковСтефан Вороников
111 золотой знак1 серебряный знак3 бронзовых знака
3
В вашем файле hw.py
у вас где-то в строке символ и за ним ещё что-то — вы его не видите, потому он где-то за правым краем окна.
Проходите каждую строку а на каждой из ней нажмите на клавиатуре клавишу End.
Потом излишние символы удалите, файл сохраните и снова напишите
python hw.py
ответ дан 2 авг 2018 в 16:24
MarianDMarianD
14.1k3 золотых знака18 серебряных знаков29 бронзовых знаков
2
Кодировку стоит проверить, должна быть utf-8, у меня такое былоЮ если файл в cp1251 сохранен
ответ дан 27 мар 2019 в 2:39
0
Почему возникает данная ошибка при запуске любого скрипта питон?
SyntaxError: unexpected character after line continuation character
Получаю данную ошибку при запуске любого файла питон, в чем может быть причина?!
-
Вопрос заданболее года назад
-
5389 просмотров
Пригласить эксперта
SyntaxError: unexpected character after line continuation character
У тебя в строке где-то болтается символ вне строковой константы.
Знак деления не перепутал, случаем?
-
Показать ещё
Загружается…
27 мая 2023, в 18:36
300000 руб./за проект
27 мая 2023, в 18:18
30000 руб./за проект
27 мая 2023, в 17:14
1000 руб./за проект
Минуточку внимания
Table of Contents
Hide
- SyntaxError: unexpected character after line continuation character.
- Fixing unexpected character after line continuation character
- Using backslash as division operator in Python
- Adding any character right after the escape character
- Adding any character right after the escape 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.
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.
- Using backslash as division operator in Python
- Adding any character right after the escape character
- Adding new line character in a string without enclosing inside the parenthesis
Also read IndentationError: unexpected indent
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= ab
print(c)
# Output
File "c:ProjectsTryoutslistindexerror.py", line 11
c= ab
^
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:ProjectsTryoutslistindexerror.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:ProjectsTryoutslistindexerror.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")
Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.
Sign Up for Our Newsletters
Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.
By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.
The Python line continuation character lets you continue a line of code on a new line in your program. The line continuation character cannot be followed by any value.
If you specify a character or statement after a line continuation character, you encounter the “SyntaxError: unexpected character after line continuation character” error.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
In this guide, we talk about what this error means and why it is raised. We walk through two examples of this error in action so you can learn how to use it in your code.
SyntaxError: unexpected character after line continuation character
The line continuation character lets you write a long string over multiple lines of code. This character is useful because it makes code easier to read. The line continuation character is a backslash (“”).
Whereas it can be hard to follow a really long line of code, one line of code divided across multiple lines is easier to follow.
The line continuation character is commonly used to break up code or to write a long string across multiple lines of code:
url = "https://careerkarma.com" "/blog/python-syntaxerror-unexpected-character-after" "line-continuation-character"
We have broken up our string into three lines. This makes it easier to read our code.
Two scenarios when this error could be raised include:
- Using a backslash instead of a forward slash as a division operator
- Adding a new line to a string without enclosing the new line character in parenthesis
We’ll talk through each of these scenarios one-by-one.
Scenario #1: Division Using a Backslash
Here, we write a program that calculates a person’s body mass index (BMI). To start, we need to ask a user to insert their height and weight into a Python program:
height = input("What is your height? ") weight = input("What is your weight? ")
Next, we calculate the user’s BMI. The formula for calculating a BMI value is:
“Kg” is a person’s weight in kilograms. “m2” is the height of a person squared. Translated into Python, the formula to calculate a BMI looks like this:
bmi = float(weight) (float(height) * 2) print("Your BMI is: " + str(bmi))
We convert the values of “weight” and “height” to floating point numbers so that we can perform mathematical functions on them.
We then print a user’s BMI to the console. We convert “bmi” to a string using the str() method so that we can concatenate it to the “Your BMI is: ” message. We round the value of “bmi” to two decimal places using the round() method.
Let’s run our code:
File "main.py", line 4 bmi = float(weight) (float(height) * 2) ^ SyntaxError: unexpected character after line continuation character
We’ve encountered an error. This is because we have used “” as the division operator instead of the “/” sign. We can fix our code by using the “/” division operator:
bmi = float(weight) / (float(height) * 2) print("Your BMI is: " + str(round(bmi, 2)))
Our code returns:
What is your height? 1.70 What is your weight? 63 Your BMI is: 18.53
Our code has successfully calculated the BMI of a user.
Scenario #2: Using the New Line Character Incorrectly
Next, we write a program that writes a list of ingredients to a file. We start by defining a list of ingredients for a shortbread recipe:
ingredients = [ "150g plain flour", "100g butter, chilled an cubed", "50g caster sugar" ]
Next, we open up a file called “shortbread_recipe.txt” to which we will write our list of ingredients:
with open("shortbread_recipe.txt", "w+") as ingredients_file: for i in ingredients: ingredients_file.write(i + n)
This code loops through every ingredient in the “ingredients” variable. Each ingredient is written to the ingredients file followed by a new line character in Python (“n”). This makes sure that each ingredient appears on a new line.
Let’s run our Python code:
File "main.py", line 9 ingredients_file.write(i + n) ^ SyntaxError: unexpected character after line continuation character
Our code returns an error. This is because we have not enclosed our new line character in quotation marks.
While the new line character is a special character, it must be enclosed within quotation marks whenever it is used. This is because Python treats “” as a line continuation character.
To solve the error in our code, we need to enclose the newline character in double quotes:
with open("shortbread_recipe.txt", "w+") as ingredients_file: for i in ingredients: ingredients_file.write(i + "n")
Let’s run our code. Our code returns no value to the console. A new file called “shortbread_recipe.txt” is created. Its contents are as follows:
150g plain flour 100g butter, chilled an cubed 50g caster sugar
Our code has successfully printed our list to the “shortbread_recipe.txt” file.
«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»
Venus, Software Engineer at Rockbot
Conclusion
The “SyntaxError: unexpected character after line continuation character” error is raised when you add code after a line continuation character.
To solve this error, make sure that you use the correct division operator (a forward slash) if you are performing mathematical operations. If you are using any special characters that contain a backslash, like the new line character, make sure that they are enclosed within quotation marks.
Now you’re ready to fix this error in your code!
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
- Example #1: Putting a Character after the line continuation character
- Solution
- Example #2: Division using the Line Continuation Character
- Solution
- Example #3: Incorrect Use of the New Line Character “n”
- Solution
- Summary
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“.
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.
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: {str(round(running_speed), 1)} 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: {str(round(running_speed, 1))} mph')
Our code returns:
Your speed is: 5.9 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!