Python syntaxerror: unexpected character after line continuation character エラーの修正

Haider Ali 2022年4月14日
Python syntaxerror: unexpected character after line continuation character エラーの修正

構文エラーは、プログラミング言語でよくあるエラーの 1つです。今日は、Python で syntaxerror: unexpected character after line continuation character を修正する方法を学習します。ソリューションを完全に理解するには、Python プログラミング言語のインデントについて何かを知っている必要があります。

Python の syntaxerror: unexpected character after line continuation character を修正しました

Python はインデントに敏感な言語であることを理解する必要があります。インデントを使用して、ステートメントのグループを作成します。他のプログラミング言語のようにブロック {} の代わりに、Python はインデントに依存しています。Python インデントの詳細についてはこちらをご覧ください。

したがって、Python で continue ステートメント\ステートメントを使用する場合、その直前にコードを記述することはできません。1 行下がって、そこからコードを開始する必要があります。次のコードを見てください。

#continuation in string

# wrong
print("Wrong use of line Continuation character " \ "Don't write anything after line continuation charater")

上記のコードを実行すると、continue 文字の使い方が間違っているため、このエラーが発生します。その直前に記述した場合、コードは実行されません。

# correct
print(
    "Hello I am python. I have an interseting Line continuation character which is used at the end of line or statment"
    "it tells the statment is continue"
)

上記のコード例では、Python で継続文字を使用する正しい方法を示しています。ご覧のとおり、文字が続くと、下の行から文字列を書き始めました。

具体的に理解するために、さらにいくつかの例を見てみましょう。

# Explicit Continuation
# wrong
number = 1+2 +\3+4\+ 5
print(number)
# Explicit Continuation
# correct
number = 1 + 2 + 3 + 4 + 5
print(number)

上記のコードを見ると、継続文字の前に書くことはできません。下の行からそのままコードを開始できます。もう 1つの例を参照してください。

#continuation in IF

# wrong
if True:
print("Hello Python")

# correct
if True:
    print("Hello Python")

# also correct
if True:
    print("Hello Python")

上で述べたように、Python はインデントに敏感な言語です。上記のコード例でそれを見ることができます。継続は、他のコード例で機能するのと同じように機能します。

著者: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

関連記事 - Python Error