Solve - SyntaxError: invalid character in Python

avatar

Borislav Hadzhiev

Mon Apr 25 20222 min read

Solve - SyntaxError: invalid character in Python #

The Python "SyntaxError: invalid character" occurs when we use an invalid character in our code, e.g. from copy-pasting. To solve the error, look at the line where the error message is pointing, re-write the line and remove any non-printable unicode characters.

syntaxerror invalid character

Here is an example of how the error occurs.

main.py
# ⛔️ SyntaxError: invalid character '‘' (U+2018) name = ‘James Doe‘
Notice that the screenshot with the error message shows exactly where the error occurred with an arrow pointing at the quote character.

The example doesn't use single quotes, instead it uses some other quote character that is not supported.

The best way to solve the error is to re-write the line that the error message points to (especially if you copy-pasted it from somewhere).

main.py
name = 'James Doe'

Now we used single quotes, so the error is resolved.

Here is another example.

main.py
# ⛔️ SyntaxError: invalid character ',' (U+FF0C) names = ['Alice''Bob']

We didn't use a regular comma which caused the error.

The error message shows exactly where the error occurred.

syntaxerror invalid character 2

Once I rewrite the code to use a regular comma, the error is solved.

main.py
names = ['Alice','Bob']
The best way to solve the error is to simply rewrite your code because there might be non-printable (invisible) unicode characters that cause your issue.

Especially if you copy-pasted the code from somewhere and your IDE doesn't take care of removing these characters, it's very hard to track them down.

You can try checking for non-printable unicode characters in your code by pasting your code in a tool like this one.

However, the best way to solve the error is to look at the line of code the error message points to and rewrite it completely.

Make sure your keyboard is set in the correct language as using a punctuation character from a different language often causes the error.

Use the search field on my Home Page to filter through my more than 1,000 articles.