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

by | Programming, Python, Tips

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.

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!

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!