Питон ошибка unexpected character after line continuation character

I am having problems with this Python program I am creating to do maths, working out and so solutions but I’m getting the syntaxerror: «unexpected character after line continuation character in python»

this is my code

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

My problem is with 1.5 I have tried 1.5 but it doesn’t work

Using python 2.7.2

asked Oct 17, 2011 at 9:40

Arcticfoxx's user avatar

0

The division operator is /, not

answered Oct 17, 2011 at 9:47

Kimvais's user avatar

KimvaisKimvais

38.1k16 gold badges107 silver badges142 bronze badges

1

The backslash is the line continuation character the error message is talking about, and after it, only newline characters/whitespace are allowed (before the next non-whitespace continues the «interrupted» line.

print "This is a very long string that doesn't fit" + 
      "on a single line"

Outside of a string, a backslash can only appear in this way. For division, you want a slash: /.

If you want to write a verbatim backslash in a string, escape it by doubling it: "\"

In your code, you’re using it twice:

 print("Length between sides: " + str((length*length)*2.6) +
       "  1.5 = " +                   # inside a string; treated as literal
       str(((length*length)*2.6)1.5)+ # outside a string, treated as line cont
                                       # character, but no newline follows -> Fail
       " Units")

answered Oct 17, 2011 at 9:46

Tim Pietzcker's user avatar

Tim PietzckerTim Pietzcker

327k58 gold badges501 silver badges559 bronze badges

0

You must press enter after continuation character

Note: Space after continuation character leads to error

cost = {"apples": [3.5, 2.4, 2.3], "bananas": [1.2, 1.8]}

0.9 * average(cost["apples"]) +  """enter here"""
0.1 * average(cost["bananas"])

answered Jan 29, 2018 at 16:01

user9284665's user avatar

1

The division operator is / rather than .

Also, the backslash has a special meaning inside a Python string. Either escape it with another backslash:

"\ 1.5 = "`

or use a raw string

r"  1.5 = "

answered Oct 17, 2011 at 9:42

NPE's user avatar

NPENPE

484k108 gold badges948 silver badges1010 bronze badges

0

Well, what do you try to do? If you want to use division, use «/» not «».
If it is something else, explain it in a bit more detail, please.

answered Oct 17, 2011 at 9:47

Andrej's user avatar

AndrejAndrej

3911 silver badge9 bronze badges

As the others already mentioned: the division operator is / rather than **.
If you wanna print the ** character within a string you have to escape it:

print("foo \")
# will print: foo 

I think to print the string you wanted I think you gonna need this code:

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

And this one is a more readable version of the above (using the format method):

message = "Length between sides: {0} \ 1.5 = {1} Units"
val1 = (length * length) * 2.6
val2 = ((length * length) * 2.6) / 1.5
print(message.format(val1, val2))

answered Oct 17, 2011 at 9:59

Nicola Coretti's user avatar

Nicola CorettiNicola Coretti

2,6452 gold badges20 silver badges22 bronze badges

This is not related to the question; just for future purpose. In my case, I got this error message when using regex. Here is my code and the correction

text = "Hey I'm Kelly, how're you and how's it going?"
import re

When I got error:

x=re.search(r'('w+)|(w+'w+)', text)

The correct code:

x=re.search(r"('w+)|(w+'w+)", text)

I’m meant to use double quotes after the r instead of single quotes.

answered Dec 9, 2022 at 15:29

Kelly's user avatar

KellyKelly

257 bronze badges

I am having problems with this Python program I am creating to do maths, working out and so solutions but I’m getting the syntaxerror: «unexpected character after line continuation character in python»

this is my code

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

My problem is with 1.5 I have tried 1.5 but it doesn’t work

Using python 2.7.2

asked Oct 17, 2011 at 9:40

Arcticfoxx's user avatar

0

The division operator is /, not

answered Oct 17, 2011 at 9:47

Kimvais's user avatar

KimvaisKimvais

38.1k16 gold badges107 silver badges142 bronze badges

1

The backslash is the line continuation character the error message is talking about, and after it, only newline characters/whitespace are allowed (before the next non-whitespace continues the «interrupted» line.

print "This is a very long string that doesn't fit" + 
      "on a single line"

Outside of a string, a backslash can only appear in this way. For division, you want a slash: /.

If you want to write a verbatim backslash in a string, escape it by doubling it: "\"

In your code, you’re using it twice:

 print("Length between sides: " + str((length*length)*2.6) +
       "  1.5 = " +                   # inside a string; treated as literal
       str(((length*length)*2.6)1.5)+ # outside a string, treated as line cont
                                       # character, but no newline follows -> Fail
       " Units")

answered Oct 17, 2011 at 9:46

Tim Pietzcker's user avatar

Tim PietzckerTim Pietzcker

327k58 gold badges501 silver badges559 bronze badges

0

You must press enter after continuation character

Note: Space after continuation character leads to error

cost = {"apples": [3.5, 2.4, 2.3], "bananas": [1.2, 1.8]}

0.9 * average(cost["apples"]) +  """enter here"""
0.1 * average(cost["bananas"])

answered Jan 29, 2018 at 16:01

user9284665's user avatar

1

The division operator is / rather than .

Also, the backslash has a special meaning inside a Python string. Either escape it with another backslash:

"\ 1.5 = "`

or use a raw string

r"  1.5 = "

answered Oct 17, 2011 at 9:42

NPE's user avatar

NPENPE

484k108 gold badges948 silver badges1010 bronze badges

0

Well, what do you try to do? If you want to use division, use «/» not «».
If it is something else, explain it in a bit more detail, please.

answered Oct 17, 2011 at 9:47

Andrej's user avatar

AndrejAndrej

3911 silver badge9 bronze badges

As the others already mentioned: the division operator is / rather than **.
If you wanna print the ** character within a string you have to escape it:

print("foo \")
# will print: foo 

I think to print the string you wanted I think you gonna need this code:

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

And this one is a more readable version of the above (using the format method):

message = "Length between sides: {0} \ 1.5 = {1} Units"
val1 = (length * length) * 2.6
val2 = ((length * length) * 2.6) / 1.5
print(message.format(val1, val2))

answered Oct 17, 2011 at 9:59

Nicola Coretti's user avatar

Nicola CorettiNicola Coretti

2,6452 gold badges20 silver badges22 bronze badges

This is not related to the question; just for future purpose. In my case, I got this error message when using regex. Here is my code and the correction

text = "Hey I'm Kelly, how're you and how's it going?"
import re

When I got error:

x=re.search(r'('w+)|(w+'w+)', text)

The correct code:

x=re.search(r"('w+)|(w+'w+)", text)

I’m meant to use double quotes after the r instead of single quotes.

answered Dec 9, 2022 at 15:29

Kelly's user avatar

KellyKelly

257 bronze badges

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

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


  • Вопрос задан

    более года назад

  • 5617 просмотров

Пригласить эксперта

SyntaxError: unexpected character after line continuation character

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


  • Показать ещё
    Загружается…

25 июн. 2023, в 13:53

2000 руб./за проект

25 июн. 2023, в 13:25

500 руб./в час

25 июн. 2023, в 11:42

600 руб./за проект

Минуточку внимания

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.

Возможно, вам также будет интересно:

  • Пишет не подключен принтер код ошибки 45
  • Питон ошибка name is not defined
  • Питон ошибка indentationerror unindent does not match any outer indentation level
  • Питон ошибка eol while scanning string literal
  • Питон если ошибка то

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии