Open In App

How to fix "SyntaxError: invalid character" in Python

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

This error happens when the Python interpreter encounters characters that are not valid in Python syntax. Common examples include:

  • Non-ASCII characters, such as invisible Unicode characters or non-breaking spaces.
  • Special characters like curly quotes (, ) or other unexpected symbols.

How to Resolve:

  • Check the error message, which will indicate the line and position of the invalid character.
  • Open the file in a text editor and carefully review the specified line for problematic characters.

Replace Problematic Quotes

If you copied code from a document or website, it might have curly quotes (, , , ) instead of standard quotes (" or ').

Fix: Replace curly quotes with standard quotes.
Example:

print(“Hello, World!”)  # Invalid
print("Hello, World!") # Valid

Check for Non-ASCII or Invisible Characters

Non-ASCII characters (e.g., \u00A0, zero-width spaces, or non-breaking spaces) might be present.

Fix:

  • Use a code editor that highlights special characters (e.g., VS Code, PyCharm).
  • Alternatively, use Python to detect invalid characters

Ensure Proper Indentation

Invisible characters like non-breaking spaces can cause issues in indentation.

Fix:

  • Replace all spaces with standard spaces or tabs. Use your editor's "Convert Indentation" feature if available.
  • Use this snippet to detect non-breaking spaces:
with open("script.py", "r", encoding="utf-8") as file:    
for line_number, line in enumerate(file, 1):
if '\u00A0' in line:
print(f"Non-breaking space on line {line_number}")

Verify File Encoding

If the file is saved in an incompatible encoding (e.g., not UTF-8), Python might misinterpret valid characters.

Fix:

  • Open the file in your editor and save it with UTF-8 encoding.

Next Article

Similar Reads