Syntax error unexpected character after line continuation character

Here's everything about SyntaxError: unexpected character after line continuation character in Python. Occurs when the back slash character is used incorrectly.

Here’s everything about the Python syntax error unexpected character after line continuation character:

This error occurs when the backslash character is used incorrectly.

So if you want to learn all about this Python error and how to solve it, then you’re in the right place.

Keep reading!

Polygon art logo of the programming language Python.

Young programmer having a headache while working and thinking about the deadline.

So you got SyntaxError: unexpected character after line continuation character?—don’t be afraid this article is here for your rescue and this error is easy to fix:

Syntax errors are usually the easiest to solve because they appear immediately after the program starts and you can see them without thinking about it much. It’s not like some logical rocket science error.

However, when you see the error SyntaxError: unexpected character after line continuation character for the first time, you might be confused:

What Is a Line Continuation Character in Python?

A line continuation character is just a backslash —place a backlash at the end of a line, and it is considered that the line is continued, ignoring subsequent newlines.

You can use it for explicit line joining, for example. You find more information about explicit line joining in the official documentation of Python. Another use of the backslash is to escape sequences—more about that further below.

However, here is an example of explicit line joining:

print("This is a huge line. It is very large, "
  "but it needs to be printed on the screen "
  "in one line as it is. For this, "
  "the backslash character is used.")
This is a huge line. It is very large, but I want to print it on the screen in one line as it is. For this, I use the slash character

So as you can see the output is: This is a huge line. It is very large, but it needs to be printed on the screen in one line. For this, the backslash character is used. No line breaks.

The backslash acts like glue and connects the strings to one string even when they are on different lines of code.

When to Use a Line Continuation Character in Python?

You can break lines of code with the backslash for the convenience of code readability and maintainability:

The PEP 8 specify a maximum line length of 79 characters—PEP is short for Python Enhancement Proposal and is a document that provides guidelines and best practices on how to write Python code.

However, you don’t need the backslash when the string is in parentheses. Then you can just do line breaks without an line continuation character at all. Therefore, in the example above, you didn’t need to use the backslash character, as the entire string is in parentheses ( … ).

However, in any other case you need the backslash to do a line break. For example (the example is directly from the official Python documentation):

with open('/path/to/some/file/you/want/to/read') as file_1, 
  open('/path/to/some/file/being/written', 'w') as file_2:

file_2.write(file_1.read())
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-1-68f8b9fb51ba> in <module>()
----> 1 with open('/path/to/some/file/you/want/to/read') as file_1,      open('/path/to/some/file/being/written', 'w') as file_2:
      2     file_2.write(file_1.read())

FileNotFoundError: [Errno 2] No such file or directory: '/path/to/some/file/you/want/to/read'

Why all that talking about this backslash? Here is why:

The error SyntaxError: unexpected character after line continuation character occurs when the backslash character is incorrectly used. The backslash is the line continuation character mentioned in the error!

Examples of “SyntaxError: Unexpected Character After Line Continuation Character” in Python

Here are examples of the character after-line continuation character error:

Example #1

The error occurs when you add an end-of-line character or line continuation character as a list item: 

)lst = [1, 2, 3]
lst.append(n)
lst
  File "<ipython-input-3-d34db7a971ff>", line 2
    lst.append(n)
                  ^
SyntaxError: unexpected character after line continuation character

Easy to fix—just put the backslash in quotes:

lst = [1, 2, 3]
lst.append("n")
lst
[1, 2, 3, 'n']

Example #2

You want to do a line break after printing something on the screen:

st = "python"
print(st, n)
  File "<ipython-input-31-8b8b9a0ca1c2>", line 2
    print(st, n)
                 ^
SyntaxError: unexpected character after line continuation character

Easy to fix, again—the backslash goes in to quotes:

st = "python"
print(st, "n")
python

Perhaps you want to add a new line when printing a string on the screen, like this. 

Example #3

Mistaking the slash / for the backslash —the slash character is used as a division operator:

print(164)
  File "<ipython-input-7-736f22f93e09>", line 1
    print(164)
               ^
SyntaxError: unexpected character after line continuation character

Another easy syntax error fix—just replace the backslash with the slash /:

print(16/4)
4.0

Example #5

However, when a string is rather large, then it’s not always that easy to find the error on the first glance.

Here is an example from Stack Overflow:

length = 10
print("Length between sides: " + str((length * length) * 2.6) + "  1.5 = " + str(((length * length) * 2.6)  1.5) + " Units")
  File "<ipython-input-11-7ea3023b0bea>", line 2
    print("Length between sides: " + str((length*length)*2.6) + "  1.5 = " + str(((length*length)*2.6)1.5)+ " Units")
                                                                                                                       ^
SyntaxError: unexpected character after line continuation character

The line of code contains several backslashes —so you need to take a closer look.

Split the line of code into logical units and put each unit on separate line of code. This simplifies the debugging:

st = "Length between sides: "
st += str((length * length) * 2.6)
st += "  1.5 = "
x = ((length * length) * 2.6)  1.5
st += str(x)
st += " Units"
print(st)
  File "<ipython-input-14-6e37321ec16d>", line 4
    x = ((length*length)*2.6)1.5
                                 ^
SyntaxError: unexpected character after line continuation character

Now you can easily see where the backslash is missing—with a sharp look at the code itself or through the debugger output. A backslash misses after the 1.5 in line of code #4.

So let’s fix this:

st = "Length between sides: "
st += str((length * length) * 2.6)
st += "  1.5 = "
x = ((length * length) * 2.6)  1.5 
st += str(x)
st += " Units"
print(st)

Example #6

Another common case of this error is writing the paths to Windows files without quotes. Here is another example from Stack Overflow:

f = open(C\python\temp\1_copy.cp,"r") 
lines = f.readlines()

for i in lines:  
  thisline = i.split(" ")
  File "<ipython-input-16-b393357b8e86>", line 1
    f = open(C\python\temp\1_copy.cp,"r")
                                               ^
SyntaxError: unexpected character after line continuation character

The full path to the file in code of line #1 must be quoted “”. Plus, a colon : is to be placed after the drive letter in case of Windows paths:

f = open("C:\python\temp\1_copy.cp","r") 
lines = f.readlines()

for i in lines:  
  thisline = i.split(" ")

The Backslash as Escape Character in Python

The backslash is also an escape character in Python:

Use the backslash to escape service characters in a string.

For example, to escape a tab or line feed service character in a string. And because the backslash is a service character on its own (remember, it’s used for line continuation), it needs to be escaped too when used in a string—\.

This is why in the last example the path contains double backslashes \ instead of a single backslash in line of code #1.

However, you don’t need any escapes in a string when you use a raw string. Use the string literal r to get a raw string. Then the example from above can be coded as:

f = open(r"C:pythontemp1_copy.cp","r")

No backslash escapes at all, yay!

Another use case for an escape are Unicode symbols. You can write any Unicode symbol using an escape sequence.

For example, an inverted question mark ¿ has the Unicode 00BF, so you can print it like this: 

print("u00BF")

Additional Examples of “SyntaxError: Unexpected Character After Line Continuation Character” in Python

Here are more common examples of the unexpected character after line continuation character error:

Example #7

Often, you don’t have a specific file or folder path and have to assemble it from parts. You can do so via escape sequences \ and string concatenations . However, this manual piecing together regularly is the reason for the unexpected character after line continuation character error.

But the osmodule to the rescue! Use the path.join function. The path.join function not only does the path completion for you, but also determines the required separators in the path depending on the operating system on which you are running your program.

#os separator examples?

For example:

import os
current_path = os.path.abspath(os.getcwd())
directory = "output"
textfile = "test.txt"
filename = os.path.join(current_path, directory, textfile)

Example #8

You can get the line continuation error when you try to comment out # a line after a line continuation character —you can’t do that in this way:

sonnet = "From fairest creatures we desire increase,n" #line one
"That thereby beauty's rose might never die,n" #line two
"But as the riper should by time decease,n" #line three
"His tender heir might bear his memoryn" #line four
print(sonnet)
  File "<ipython-input-21-0a5c2224492e>", line 1
    sonnet = "From fairest creatures we desire increase,n" #line one
                                                                      ^
SyntaxError: unexpected character after line continuation character

Remember from above that within parenthesis () an escape character is not needed? So put the string in parenthesis (), easy as that—and voila you can use comments # where ever you want.

You can put dummy parentheses, simply for hyphenation purposes:

sonnet = ("From fairest creatures we desire increase,n" #line one 
"That thereby beauty's rose might never die,n" #line two 
"But as the riper should by time decease,n" #line three 
"His tender heir might bear his memoryn") #line four 
print(sonnet)
From fairest creatures we desire increase,
That thereby beauty's rose might never die,
But as the riper should by time decease,
His tender heir might bear his memory

Example #9

Another variation of the unexpected character after line continuation character error is when you try to run a script from the Python prompt. Here is a script correctly launched from the Windows command line:

c:temp>python c:temphelloworld.py
Hello, World!

However, if you type python first and hit enter, you will be taken to the Python prompt.

Here, you can directly run Python code such as print(“Hello, World!”). And if you try to run a file by analogy with the Windows command line, you will get an error:

d:temp>python

Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information.

>>> d:temphelloworld.py
File "", line 1

d:temphelloworld.py
                    ^
SyntaxError: unexpected character after line continuation character

Here’s more Python support:

  • 3 Ways to Solve Series Objects Are Mutable and Cannot be Hashed
  • How to Solve ‘Tuple’ Object Does Not Support Item Assignment
  • How to Solve SyntaxError: Invalid Character in Identifier
  • ImportError: Attempted Relative Import With No Known Parent Package
  • IndentationError: Unexpected Unindent in Python (and 3 More)
Table of Contents
Hide
  1. SyntaxError: unexpected character after line continuation character.
  2. Fixing unexpected character after line continuation character
  3. Using backslash as division operator in Python
  4. Adding any character right after the escape character
  5. 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.

  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

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")

Avatar Of Srinivas Ramakrishna

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.

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!

In python, the error SyntaxError: unexpected character after line continuation character occurs when the escape character is misplaced in the string or characters added after line continuation character. The “” escape character is used to indicate continuation of next line. If any characters are found after the escape character “”, The python interpreter will throw the error unexpected character after line continuation character in python language.

The string in python contains escape sequence characters such as n, , t etc. If you miss or delete quotes in the string, the escape character “” in the string is the end of the current line. If any characters are found after the “” is considered invalid. Python therefore throws this error SyntaxError: Unexpected character after line continuation character.

Here, we see the common mistakes that causes this SyntaxError: Unexpected character after line continuation character error and how to fix this error. The error would be thrown as like below.

  File "/Users/python/Desktop/test.py", line 1
    z=n
       ^
SyntaxError: unexpected character after line continuation character
[Finished in 0.1s with exit code 1]

Root Cause

The back slash “” is considered to be th end of line in python. If any characters are added after the back slash is deemed invalid. The back slash “” is also used as an escape sequence character in the python string. For instance “n” is a new line character. “t” is a tab in python.

If the quotation in the string is missing or deleted, the escape character “” will be treated as the end of the line. The characters added after that will be considered invalid. Therefore, Python throws this SyntaxError: unexpected character after line continuation character error

How to reproduce this error

If any characters are added after the back slash “”, they will be treated as invalid. Adding the python code after the end of line character “” will throw this error SyntaxError: unexpected character after line continuation character. In this example, the character “n” in the “n” is considered invalid.

z=n
print z

Output

  File "/Users/python/Desktop/test.py", line 1
    z=n
       ^
SyntaxError: unexpected character after line continuation character
[Finished in 0.0s with exit code 1]

Solution 1

The python string should be enclosed with single or double quotes. Check the string that has been properly enclosed with the quotations. If a quotation is missed or deleted, correct the quotation. This is going to solve this error. The code above will be fixed by adding the quotation in “n”.

z="n"
print z

Output


[Finished in 0.0s]

Solution 2

If you want to add the “n” as a character with no escape sequence operation, then “r” should be prefixed along with the string. This will print the characters as specified within the string. The code below will be printed as “n” instead of a new line character.

z=r"n"
print z

Output

n
[Finished in 0.1s]

Solution 3

If a character is added after the end of the line, the character should be moved to the next line. When the copy and paste operation is performed, the new line characters are missing. Fixing the intent of the code will resolve this SyntaxError: unexpected character after line continuation character error.

x = 3
y = 2
if x==3  or y==2 :
	print x

Output

  File "/Users/python/Desktop/test.py", line 3
    if x==3  or y==2 :
                      ^
SyntaxError: unexpected character after line continuation character
[Finished in 0.0s with exit code 1]

Solution

x = 3
y = 2
if x==3 
	or y==2 :
	print x

Output

3
[Finished in 0.0s]

Solution 4

If a white space is added after the end of the “” line character, it should be removed. The character is not visible in the code. If the python interpreter throws this error and no characters are visible, a whitespace must be availabe after that. Removing all whitespace after the end of the “” character will resolve this error.

x = 3
y = 2
if x==3               --> a space available after 
	or y==2 :
	print x

Output

  File "/Users/python/Desktop/test.py", line 3
    if x==3  or y==2 :
                      ^
SyntaxError: unexpected character after line continuation character
[Finished in 0.0s with exit code 1]

Solution

x = 3
y = 2
if x==3 
	or y==2 :
	print x

Output

3
[Finished in 0.0s]

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.

Get offers and scholarships from top coding schools illustration

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

Email

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.

Venus profile photo

«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!

Table of Contents

  • What Is a Line Continuation Character in Python?
  • Syntaxerror: “Unexpected Character After Line Continuation Character in Python”- Occurrences and Solutions
    • Using escape character instead of the division operator / in mathematical expressions
    • Adding the newline character n to a string using the + operator
    • Adding space or tab after the line continuation character
  • Conclusion

While programming in python, sometimes we need to write very long statements. For better presentation, we often use line continuation character. However, if you don’t use line continuation character correctly, SyntaxError occurs with the message “SyntaxError: unexpected character after line continuation character in python”. In this article, we will discuss the possible cases when this error can occur and how you can overcome this syntax error.

What Is a Line Continuation Character in Python?

The escape character is used as the line continuation character in python. We often use the line continuation character to split a statement as shown below.

number1=10

number2=20

number3=30  

number4=40

number5=50

output=number1+number1*number2+number3*number1*number2

+number4*number5

print(«The output is:»,output)

Output:

We can also split a single string into multiple lines using the line continuation character as follows.

myStr = «Hi am a long string. I am so long that I cannot fit into a single line in the source code.»

        «So, they have moved us to the next  line.»

print(myStr)

Output:

Hi am a long string. I am so long that I cannot fit into a single line in the source code.So, they have moved us to the next  line.

Let us now discuss the situations where using the line continuation character leads to error. 

Syntaxerror: “Unexpected Character After Line Continuation Character in Python”- Occurrences and Solutions

Using escape character instead of the division operator / in mathematical expressions

The most common case when the syntax error occurs with the message “unexpected character after line continuation character in python” occurs when we use the escape character instead of the division operator / in mathematical expressions. You can observe this in the following example. 

num1=10

num2=5

output=num1num2

Output:

/usr/lib/python3/distpackages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn‘t match a supported version!

  warnings.warn(«urllib3 ({}) or chardet ({}) doesn’t match a supported «

  File «/home/aditya1117/PycharmProjects/pythonProject/string1.py«, line 3

    output=num1num2

                   ^

SyntaxError: unexpected character after line continuation character

This kind of error is mostly committed by new programmers who are just getting along with the syntax of the programming language. In this case, you can easily avoid this error using the division operator instead of the line continuation character as follows.

num1 = 10

num2 = 5

output = num1 / num2

print(output)

Output:

Adding the newline character n to a string using the + operator

Sometimes, you may add the newline character n to a string using the + operator as follows.

myStr = «Hi am a long string.»

print(myStr+n)

Output:

/usr/lib/python3/distpackages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn‘t match a supported version!

  warnings.warn(«urllib3 ({}) or chardet ({}) doesn’t match a supported «

  File «/home/aditya1117/PycharmProjects/pythonProject/string1.py«, line 2

    print(myStr+n)

                  ^

SyntaxError: unexpected character after line continuation character

Here, we have tried to print a new line along with the string by adding it to the string. However, this leads to syntax error saying “unexpected character after line continuation character in python”. This is so because n works as the newline character only when it is used as a string literal. In this case, is considered as a line continuation character, and n is considered to be an unexpected character because there are no characters allowed after a line continuation character. In this case, you can avoid the syntax error by simply using the newline character as a string as shown in the following example.

myStr = «Hi am a long string.»

print(myStr+«n»)

Output:

Adding space or tab after the line continuation character

In the above two cases, the errors are easily identifiable. However, if it happens that you put a space or tab after the line continuation character, the program will again run into the syntax error and will display the error message “unexpected character after line continuation character in python”. For instance, look at the example below.

number1=10

number2=20

number3=30  

number4=40

number5=50

output=number1+number1*number2+number3*number1*number2

+number4*number5

print(«The output is:»,output)

Output:

/usr/bin/python3.8 /home/aditya1117/PycharmProjects/pythonProject/string1.py

/usr/lib/python3/distpackages/requests/__init__.py:89: RequestsDependencyWarning: urllib3 (1.26.7) or chardet (3.0.4) doesn‘t match a supported version!

  warnings.warn(«urllib3 ({}) or chardet ({}) doesn’t match a supported «

  File «/home/aditya1117/PycharmProjects/pythonProject/string1.py«, line 6

    output=number1+number1*number2+number3*number1*number2

                                                           ^

SyntaxError: unexpected character after line continuation character

Here, you cannot identify that there is a space character after the line continuation character. However, the space character is present and it has caused the syntax error in the program. So, if you are facing a syntax error with the message “unexpected character after line continuation character in python” and you are not able to identify what the mistake is, make sure that you press the enter key just after the line continuation character and there are no spaces after it. IN this way, you will be able to remove the syntax error.

Conclusion

In this article, we have discussed how the syntax error with the message “SyntaxError: unexpected character after line continuation character in python” occurs and how we can avoid it. 

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Содержание

  1. SyntaxError: unexpected character after line continuation character
  2. SyntaxError: unexpected character after line continuation character.
  3. Fixing unexpected character after line continuation character
  4. Using backslash as division operator in Python
  5. Adding any character right after the escape character
  6. Adding any character right after the escape character
  7. [Solved] SyntaxError: unexpected character after line continuation character
  8. ❌ Problem: you accidentally put something after the backslash
  9. ✅ Fix: just remove the stuff after the backslash or put it on a new line
  10. ❌ Problem: you didn’t put a string containing a special character in quotes
  11. ✅ Fix: add the missing quote(s)
  12. ☝️ Tip: use syntax hilighting!
  13. ❌ Problem: you’re using a backslash for division (why?)
  14. ✅ Fix: use a forward slash for division 🤦‍♂️
  15. Conclusion
  16. 9 Examples of Unexpected Character After Line Continuation Character (Python)
  17. SyntaxError: Unexpected Character After Line Continuation Character in Python
  18. What Is a Line Continuation Character in Python?
  19. When to Use a Line Continuation Character in Python?
  20. Examples of “SyntaxError: Unexpected Character After Line Continuation Character” in Python
  21. Example #1
  22. Example #2
  23. Example #3
  24. Example #5
  25. Example #6
  26. The Backslash as Escape Character in Python
  27. Additional Examples of “SyntaxError: Unexpected Character After Line Continuation Character” in Python
  28. Example #7
  29. Example #8
  30. Example #9

SyntaxError: unexpected character after line continuation character

Table of Contents Hide

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

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.

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

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.

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

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.

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

Источник

[Solved] SyntaxError: unexpected character after line continuation character

This Python error occurs when you accidentally put a character right after a backslash ( ) that isn’t inside a string. This can happen for many reasons, for example, if you forget to put a newline ( n ) in quotes or if you’re mistakenly using a backslash for division. Fix this easily by making sure nothing follows a that is outside of a string.

Sometimes lines get a little too long in your Python code. The old rule of thumb is to not let your lines get longer than 80 characters. But that was before widescreen monitors. Nowadays, it’s more like 120 characters. Really, it comes down to personal preference or whatever your team decides is the style to go with.

Either way, there’s only one way to break up a long line, and that’s with the line continuation character:

Though this might look a little funky if you’ve never seen it done before, the above code is perfectly valid. The backslash simply tells the Python interpreter “hey, this line continues below, so pretend the next line is also on this line”.

If you don’t use the continuation character correctly, however, you can end up with “SyntaxError: unexpected character after line continuation character”. Let’s look at some ways this can occur!

❌ Problem: you accidentally put something after the backslash

We’ll start with the most obvious one: you did just make a mistake. I know, I know. You don’t make mistakes. I don’t either. It was probably someone else. But now it’s your problem, because it’s 4:58 on a Friday afternoon and your branch won’t merge because of a syntax error.

Here’s an example of some code that will cause this problem:

This is the same example from above, except there’s a stray n after the . If you run this code, you’ll get the following stack trace:

As you can see, the Python interpreter is pointing right at the problem. It’s easy to make this particular mistake, because you were already putting n s in your string, so you may have slipped up and accidentally put one after the continuation character as well. Or someone else did. But we both know it was you. Don’t worry, I’m no snitch.

This can also happen if you didn’t actually put the second line on a new line:

✅ Fix: just remove the stuff after the backslash or put it on a new line

This one is easy to fix: just delete the extra stuff or put it on a new line like so:

Now we’re back in business!

❌ Problem: you didn’t put a string containing a special character in quotes

You can also easily have this problem if you forget one or more quotes in a string that contains a special character, such as t or n :

As you can see here, all we wanted to do was have a string containing the word “foo” that is tabbed over once (like this: » foo» ). But, instead, we get the following error message:

✅ Fix: add the missing quote(s)

This one’s an easy fix too. All we have to do is add the missing quotation marks and it should work as expected:

That’s all there is to it!

☝️ Tip: use syntax hilighting!

This should come as no surprise, but you can avoid mistakes like this by using a text editor or integrated development environment (IDE) that has syntax highlighting like the code blocks you see above do. If you’re stuck on a system that has vanilla vi installed or something, then I guess you’re out of luck. But, if you have the ability to do so, try:

  • vim – this might already be installed on the system you’re editing Python code on – try it and see! You can save yourself a lot of hassle. If you’re on a Debian based Linux disto such as Ubuntu, and you’re in the sudoers list, you can install it with sudo apt-get install vim .
  • PyCharm – this is a great, full-featured Python IDE by JetBrains. Don’t let the price tag scare you, there’s a free version called “Community Edition” or “CE”. Install that one and it won’t harass you for a license key when you go to install it
  • Atom – this one’s a personal favorite. It’s an all-purpose text editor with tons of plugins, similar to Notepad++ on Windows systems, or Sublime Text on Mac. But, this one’s cross-platform and best of all, it’s free. Which is my favorite price!

❌ Problem: you’re using a backslash for division (why?)

This is a weird one, but I’ve seen it happen before. Not me of course, I would never do this. But someone has. For the sake of completeness, here’s what the wrong thing looks like:

This, as you can imagine, isn’t going to give you 0.5 . It’s going to give you a stack trace. And that stack trace is going to look like this:

No surprises here. Let’s fix this.

✅ Fix: use a forward slash for division 🤦‍♂️

Alright kids, gather ’round. Grandpa Bill is going to lay down a life lesson for you: you divide with a forward slash. Like this:

And there you have it.

Conclusion

In this article, we covered what causes the Python error “SyntaxError: unexpected character after line continuation character”. It’s always caused by something coming after a backslash that’s not within a string. Inside a string, the character is used to denote a special character, like n . Outside a string, like in your regular Python code, it’s a continuation character, which means it tells the Python interpreter that the current line is continued on the next one. It can’t have anything after it, or you’ll get this error.

We also discussed why you should use a text editor (or IDE) with syntax highlighting. This will save you a lot of trouble in the long run.

That’s all for now, happy coding!

About the Author

Bill is a senior software engineer with 23 years of experience. He specializes in Python, Javascript, C/C++, DevOps, test driven development, and making sure your code isn’t terrible.

Источник

9 Examples of Unexpected Character After Line Continuation Character (Python)

Here’s everything about the Python syntax error unexpected character after line continuation character:

This error occurs when the backslash character is used incorrectly.

So if you want to learn all about this Python error and how to solve it, then you’re in the right place.

SyntaxError: Unexpected Character After Line Continuation Character in Python

So you got SyntaxError: unexpected character after line continuation character?—don’t be afraid this article is here for your rescue and this error is easy to fix:

Syntax errors are usually the easiest to solve because they appear immediately after the program starts and you can see them without thinking about it much. It’s not like some logical rocket science error.

However, when you see the error SyntaxError: unexpected character after line continuation character for the first time, you might be confused:

What Is a Line Continuation Character in Python?

A line continuation character is just a backslash —place a backlash at the end of a line, and it is considered that the line is continued, ignoring subsequent newlines.

You can use it for explicit line joining, for example. You find more information about explicit line joining in the official documentation of Python. Another use of the backslash is to escape sequences—more about that further below.

However, here is an example of explicit line joining:

So as you can see the output is: This is a huge line. It is very large, but it needs to be printed on the screen in one line. For this, the backslash character is used. No line breaks.

The backslash acts like glue and connects the strings to one string even when they are on different lines of code.

When to Use a Line Continuation Character in Python?

You can break lines of code with the backslash for the convenience of code readability and maintainability:

The PEP 8 specify a maximum line length of 79 characters—PEP is short for Python Enhancement Proposal and is a document that provides guidelines and best practices on how to write Python code.

However, you don’t need the backslash when the string is in parentheses. Then you can just do line breaks without an line continuation character at all. Therefore, in the example above, you didn’t need to use the backslash character, as the entire string is in parentheses ( … ).

However, in any other case you need the backslash to do a line break. For example (the example is directly from the official Python documentation):

Why all that talking about this backslash? Here is why:

The error SyntaxError: unexpected character after line continuation character occurs when the backslash character is incorrectly used. The backslash is the line continuation character mentioned in the error!

Examples of “SyntaxError: Unexpected Character After Line Continuation Character” in Python

Here are examples of the character after-line continuation character error:

Example #1

The error occurs when you add an end-of-line character or line continuation character as a list item:

Easy to fix—just put the backslash in quotes:

Example #2

You want to do a line break after printing something on the screen:

Easy to fix, again—the backslash goes in to quotes:

Perhaps you want to add a new line when printing a string on the screen, like this.

Example #3

Mistaking the slash / for the backslash —the slash character is used as a division operator:

Another easy syntax error fix—just replace the backslash with the slash /:

Example #5

However, when a string is rather large, then it’s not always that easy to find the error on the first glance.

Here is an example from Stack Overflow:

The line of code contains several backslashes —so you need to take a closer look.

Split the line of code into logical units and put each unit on separate line of code. This simplifies the debugging:

Now you can easily see where the backslash is missing—with a sharp look at the code itself or through the debugger output. A backslash misses after the 1.5 in line of code #4.

So let’s fix this:

Example #6

Another common case of this error is writing the paths to Windows files without quotes. Here is another example from Stack Overflow:

The full path to the file in code of line #1 must be quoted “”. Plus, a colon : is to be placed after the drive letter in case of Windows paths:

The Backslash as Escape Character in Python

The backslash is also an escape character in Python:

Use the backslash to escape service characters in a string.

For example, to escape a tab or line feed service character in a string. And because the backslash is a service character on its own (remember, it’s used for line continuation), it needs to be escaped too when used in a string—\.

This is why in the last example the path contains double backslashes \ instead of a single backslash in line of code #1.

However, you don’t need any escapes in a string when you use a raw string. Use the string literal r to get a raw string. Then the example from above can be coded as:

No backslash escapes at all, yay!

Another use case for an escape are Unicode symbols. You can write any Unicode symbol using an escape sequence.

For example, an inverted question mark ¿ has the Unicode 00BF, so you can print it like this:

Additional Examples of “SyntaxError: Unexpected Character After Line Continuation Character” in Python

Here are more common examples of the unexpected character after line continuation character error:

Example #7

Often, you don’t have a specific file or folder path and have to assemble it from parts. You can do so via escape sequences \ and string concatenations . However, this manual piecing together regularly is the reason for the unexpected character after line continuation character error.

But the osmodule to the rescue! Use the path.join function. The path.join function not only does the path completion for you, but also determines the required separators in the path depending on the operating system on which you are running your program.

#os separator examples?

Example #8

You can get the line continuation error when you try to comment out # a line after a line continuation character —you can’t do that in this way:

Remember from above that within parenthesis () an escape character is not needed? So put the string in parenthesis (), easy as that—and voila you can use comments # where ever you want.

You can put dummy parentheses, simply for hyphenation purposes:

Example #9

Another variation of the unexpected character after line continuation character error is when you try to run a script from the Python prompt. Here is a script correctly launched from the Windows command line:

However, if you type python first and hit enter, you will be taken to the Python prompt.

Here, you can directly run Python code such as print(“Hello, World!”). And if you try to run a file by analogy with the Windows command line, you will get an error:

Источник

Понравилась статья? Поделить с друзьями:
  • Syntax error python что это
  • Syntax error python примеры
  • Syntax error python как вызвать
  • Syntax error python pip install
  • Syntax error python expected