• Register
0 votes
2.2k views

Problem :

My Python program is giving below error
python unexpected character after line continuation character
6.9k points

Please log in or register to answer this question.

3 Answers

0 votes

Solution:

Here backslash \ is the line continuation character the error message is talking about, and after it, only newline characters/whitespace are allowed

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: "\\"

Further Readings:

https://github.com/maxpumperla/deep_learning_and_the_game_of_go/issues/5

38.6k points
edited by
0 votes

The backslash is the line continuous character, about the error message is talking and after it, only the new line characters and white spaces are allowed. Before the next non-whitespace continuous the “interrupted” line.

print “This is the very long sentence and does not seems to be fit “ \

           “on a single line”.

Multiple string literals:

If the multiple string literals are written sequentially, then they can be concatenated into one string like;

s = 'aaa' 'bbb'

print(s)

# aaabbb

We can write the long string into multiple lines of code as follows;

'%E3%83%97%E3%83%AD%E3%82%B0%E3%83'\

    '%A9%E3%83%9F%E3%83%B3%E3%82%B0%E8%A8%80%E8%AA%9E'

print(s)

# https://ja.wikipedia.org/wiki/%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0%E8%A8%80%E8%AA%9E

Strings surrounded by “”:

Only the string literals that are surrounded by ‘’ or “” can be concatenated if they are written consecutively. Note that in this case of variables error can occur;

 s_var = 'xxx'

# s = 'aaa' s_var 'bbb'

# SyntaxError: invalid syntax

Solution:

Use the + operator to concatenate the variables, or the variables and string literals;

s = 'aaa' + s_var + 'bbb'

print(s)

# aaaxxxbbb

You need to use the + operator to concatenate the variables, even if they are separated by a backslash (\).

s = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'\

    + s_var\

    + 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'

print(s)

# aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaxxxbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb

 

3.9k points
1 vote

Solution:

Your issue is that you miss understood the syntax of strings, you did this:

'Text '\n'another text'

As you can see here, To write strings, you can use single quotes or double-quotes. And to add a new line:

"String\n"

What you did is that you ended the first string ‘Text ‘, then you put the newline character without strings quotes, then started a new string. Python’s syntax doesn’t work in this way, I know this is a bit of confusing, but take your time understanding it. 

      94.3k points