Mon Apr 25 2022·2 min read
Photo by Valentin Salja
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.
Here is an example of how the error occurs.
# ⛔️ SyntaxError: invalid character '‘' (U+2018) name = ‘James Doe‘
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).
name = 'James Doe'
Now we used single quotes, so the error is resolved.
Here is another example.
# ⛔️ 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.
Once I rewrite the code to use a regular comma, the error is solved.
names = ['Alice','Bob']
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.