Syntax error non ascii character python

Python 2.7. Unicode Errors Simply Explained. GitHub Gist: instantly share code, notes, and snippets.

Python 2.7. Unicode Errors Simply Explained

I know I’m late with this article for about 5 years or so, but people are still using Python 2.x, so this subject is relevant I think.

Some facts first:

  • Unicode is an international encoding standard for use with different languages and scripts
  • In python-2.x, there are two types that deal with text.
    1. str is an 8-bit string.
    2. unicode is for strings of unicode code points.
      A code point is a number that maps to a particular abstract character. It is written using the notation U+12ca to mean the character with value 0x12ca (4810 decimal)
  • Encoding (noun) is a map of Unicode code points to a sequence of bytes. (Synonyms: character encoding, character set, codeset). Popular encodings: UTF-8, ASCII, Latin-1, etc.
  • Encoding (verb) is a process of converting unicode to bytes of str, and decoding is the reverce operation.
  • Python 2.x uses ASCII as a default encoding. (More about this later)

SyntaxError: Non-ASCII character

When you sees something like this

SyntaxError: Non-ASCII character 'xd0' in file /tmp/p.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

you just need to define encoding in the first or second line of your file.
All you need is to have string coding=utf8 or coding: utf8 somewhere in your comments.
Python doesn’t care what goes before or after those string, so the following will work fine too:

# -*- encoding: utf-8 -*-

Notice the dash in utf-8. Python has many aliases for UTF-8 encoding, so you should not worry about dashes or case sensitivity.

UnicodeEncodeError Explained

>>> str(u'café')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'xe9' in position 3: ordinal not in range(128)

str() function encodes a string. We passed a unicode string, and it tried to encode it using a default encoding, which is ASCII. Now the error makes sence because ASCII is 7-bit encoding which doesn’t know how to represent characters outside of range 0..128.
Here we called str() explicitly, but something in your code may call it implicitly and you will also get UnicodeEncodeError.

How to fix: encode unicode string manually using .encode('utf8') before passing to str()

UnicodeDecodeError Explained

>>> utf_string = u'café'
>>> byte_string = utf_string.encode('utf8')
>>> unicode(byte_string)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 3: ordinal not in range(128)

Let’s say we somehow obtained a byte string byte_string which contains encoded UTF-8 characters. We could get this by simply using a library that returns str type.
Then we passed the string to a function that converts it to unicode. In this example we explicitly call unicode(), but some functions may call it implicitly and you’ll get the same error.
Now again, Python uses ASCII encoding by default, so it tries to convert bytes to a default encoding ASCII. Since there is no ASCII symbol that converts to 0xc3 (195 decimal) it fails with UnicodeDecodeError.

How to fix: decode str manually using .decode('utf8') before passing to your function.

Rule of Thumb

Make sure your code works only with Unicode strings internally, converting to a particular encoding on output, and decoding str on input.
Learn the libraries you are using, and find places where they return str. Decode str before return value is passed further in your code.

I use this helper function in my code:

def force_to_unicode(text):
    "If text is unicode, it is returned as is. If it's str, convert it to Unicode using UTF-8 encoding"
    return text if isinstance(text, unicode) else text.decode('utf8')

Source: https://docs.python.org/2/howto/unicode.html

Содержание

  1. gornostal / Unicode.md
  2. Syntax error non ascii character python
  3. Комментарии ( 1 )
  4. Оставьте свой комментарий
  5. Интересные статьи:
  6. питон и русский
  7. Re: питон и русский
  8. Re: питон и русский
  9. Re: питон и русский
  10. Re: питон и русский
  11. Re: питон и русский
  12. Re: питон и русский
  13. Re: питон и русский

gornostal / Unicode.md

Python 2.7. Unicode Errors Simply Explained

I know I’m late with this article for about 5 years or so, but people are still using Python 2.x, so this subject is relevant I think.

Some facts first:

  • Unicode is an international encoding standard for use with different languages and scripts
  • In python-2.x, there are two types that deal with text.
    1. str is an 8-bit string.
    2. unicode is for strings of unicode code points.
      A code point is a number that maps to a particular abstract character. It is written using the notation U+12ca to mean the character with value 0x12ca (4810 decimal)
  • Encoding (noun) is a map of Unicode code points to a sequence of bytes. (Synonyms: character encoding, character set, codeset). Popular encodings: UTF-8, ASCII, Latin-1, etc.
  • Encoding (verb) is a process of converting unicode to bytes of str , and decoding is the reverce operation.
  • Python 2.x uses ASCII as a default encoding. (More about this later)

SyntaxError: Non-ASCII character

When you sees something like this

you just need to define encoding in the first or second line of your file. All you need is to have string coding=utf8 or coding: utf8 somewhere in your comments. Python doesn’t care what goes before or after those string, so the following will work fine too:

Notice the dash in utf-8. Python has many aliases for UTF-8 encoding, so you should not worry about dashes or case sensitivity.

str() function encodes a string. We passed a unicode string, and it tried to encode it using a default encoding, which is ASCII. Now the error makes sence because ASCII is 7-bit encoding which doesn’t know how to represent characters outside of range 0..128.
Here we called str() explicitly, but something in your code may call it implicitly and you will also get UnicodeEncodeError .

How to fix: encode unicode string manually using .encode(‘utf8’) before passing to str()

Let’s say we somehow obtained a byte string byte_string which contains encoded UTF-8 characters. We could get this by simply using a library that returns str type.
Then we passed the string to a function that converts it to unicode . In this example we explicitly call unicode() , but some functions may call it implicitly and you’ll get the same error.
Now again, Python uses ASCII encoding by default, so it tries to convert bytes to a default encoding ASCII. Since there is no ASCII symbol that converts to 0xc3 (195 decimal) it fails with UnicodeDecodeError .

How to fix: decode str manually using .decode(‘utf8’) before passing to your function.

Make sure your code works only with Unicode strings internally, converting to a particular encoding on output, and decoding str on input. Learn the libraries you are using, and find places where they return str . Decode str before return value is passed further in your code.

Источник

Syntax error non ascii character python

Для того, чтобы использовать в скриптах питона кириллические символы, нужно:

1. Использовать кодировку UTF-8 для скриптов.

2. В начале каждого PY-флайла добавить 2 строчки:

И будет счастье! 🙂

В противном случае при запуске скрипта могут возникать ошибки с текстом типа:

SyntaxError: Non-ASCII character ‘xd0’ in file /Users/user/projects/Python/Task1/MQ.py on line 15, but no encoding declared; .

Чаще всего ошибка Non-ASCII character ‘xd0’ возникает при использовании различных IDE, типа JetBrains PyCharm и т.п., если в тексте скрипта содержатся русские символы. Причем, не важно, где написаны русские буквы — в исполняемом участке кода или в комментарии — ошибка будет в обоих случаях.

Комментарии ( 1 )

У меня выводятся не кириллические символы, а их байтовая репрезентация, например:

Как с этим бороться?

Оставьте свой комментарий

  1. Опубликовать комментарий как Гость.

Интересные статьи:

SQL-задачка от Яндекса

Один товарищ рассматривал вариант устроиться на работу в Яндекс на вакансию «Асессор-разработчик». В тестовом задании была задачка на составление SQL-запроса.

Малыш и Карлсон

— Потрясающе! — удивился Малыш. — Но позвольте! Вы ведь летели с положительным тангажем.— Чего? — Карлсон открыл рот от неожиданности и чуть не подавился. — Ну. Вы летели головой вверх, слегка наклонившись вперед. При этом пропеллер должен был тянуть вас вверх и назад. Почему же вы летели вперед, а не назад? А можно посмотреть на твой пропеллер?— Конечно. — Карлсон развернулся.— С ума сойти! Я так и.

Как создать корзину на флэшке

Как известно, по умолчанию корзина Windows создается только на жестких дисках (HDD), на флэшках ее нет. Поэтому, случайно удалив что-нибудь на флешке, для восстановления приходится прибегать к помощи специальных реанимационных программ. Иногда, правда в результате воздействия вирусов на флэшках может появиться визуально похожий на Корзину объект, но это — не настоящая корзина, и в ней кроме вирусов.

Как добавить свой CSS-класс в редактор TinyMCE в Joomla

Многие создатели сайтов на Joomla используют собственные классы для различных объектов CSS. Это могут быть классы, например, для таблиц или изображений. Начиная с Joomla версии 2.5 эта популярная CMS использует поддержку технологии «Lightbox«, и теперь для получения этого эффекта не нужно устанавливать сторонние расширения, все уже реализовано в самом движке Joomla, достаточно только в редакторе.

File Cache Storage не поддерживается

После обновления Joomla до версии 3.6 или после чистой установки Joomla 3.6 возможно получения ошибки как на самом сайте (FrontEnd), так и в админке (BackEnd) сообщения об ошибке: Error displaying the error page: The file Cache Storage is not supported on this platform. Ситуация не приятная, но не все потеряно, и это можно легко исправить.

Apple iOS 11 не поддерживает 32-битные приложения

В июне 2017 прошла всемирная конференция для разработчиков на платформах Apple (WWDC — Apple Worldwide Developers Conference) на которой было официально заявлено со стороны Apple, что, операционные системы macOS High Sierra и iOS 11 все последующие за ними не будут поддерживать 32-битные программные приложения. Таким образом, на компьютеры Mac с операционной системой macOS High Sierra и на планшеты.

Как отобразить KML-трек в Garmin Pilot

Есть такое iOS-приложение — Garmin Pilot, которое можно было бы назвать замечательным, но с марта 2022 года она стало немного иным. Но, довольно грустной лирики, ибо есть люди, которые до сих пор пользуются этим приложеним не смотря ни на что. Итак, в некоторых случаях пилотам может понадобиться выполнять полет и контролировать местоположение ВС относительно некого трека, который был записан ранее. Если.

Источник

питон и русский

Подскажите пожалуйста как приучить питон к русскому? убунта 7.10 питон 2.5

при добавлении руского комантария или использования руского текста где либо еще говорит : SyntaxError: Non-ASCII character ‘xd1’ in file ./my_prog.py on line 2

Re: питон и русский

текст программы в студию

Re: питон и русский

Re: питон и русский

Re: питон и русский

sys:1: DeprecationWarning: Non-ASCII character ‘xd2’ in file ./aa on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

Как и должно быть.

Правда, у меня Питон 2.4

Re: питон и русский

>> текст программы в студию

> Зачем текст, когда он явно ругается на non-ascii символы?

Потому что оно ругается на синтаксическую ошибку.

Re: питон и русский

Крон, спасибо тебе большое — помогло. Всем так же спасибо за то что откликнулись и за скорость ответа 🙂

Re: питон и русский

>Потому что оно ругается на синтаксическую ошибку.

Всю жизнь так и ругается. Все преьензии к Гвидо 🙂

Вот, и у меня в тесте:

/work-homesrv/programming/python/smarttime $ python test.py File «test.py», line 3 SyntaxError: Non-ASCII character ‘xd0’ in file test.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

А с «# -*- coding: utf-8 -*-» — всё ок.

Gentoo, python-2.5.2-r2, но, повторюсь, эта особенность уже очень давняя.

Источник

  1. What Are ASCII Codes
  2. What Is the SyntaxError: Non-ASCII character 'xe2' in File in Python
  3. How to Fix the SyntaxError: Non-ASCII character 'xe2' in File in Python
  4. Conclusion

Python SyntaxError: Non-Ascii Character xe2 in File

This error indicates that you are writing a Non-ASCII character in your code. At the compile time, the interpreter gets confused and throws the SyntaxError: Non-ASCII character 'xe2'.

ASCII characters use the same encoding as the first 128 characters of the UTF-8, so ASCII text is compatible with UTF-8. First, you must understand the difference between ASCII and Non-ASCII characters.

What Are ASCII Codes

ASCII is the most popular character encoding format for text data on computers and the internet (American Standard Code for Information Interchange).

There are distinct values for 128 extra alphabetic, numeric, special, and control characters in ASCII-encoded data.

What Is the SyntaxError: Non-ASCII character 'xe2' in File in Python

The core reason behind this error is that you are reading a character that isn’t recognized by your Python compiler.

For instance, let’s try the symbol £, which the Python interpreter doesn’t recognize.

string = "£"
fp = open("test.txt", "w+")

fp.write("%s" % string)
print(string)

Output:

SyntaxError: Non-ASCII character 'xe2'

The symbol £ is not recognized by the interpreter, so it’s giving a SyntaxError: Non-ASCII character 'xe2'.

How to Fix the SyntaxError: Non-ASCII character 'xe2' in File in Python

Here we have included the statement #coding: utf-8 on the program’s top. This code will create a file test.txt in which the £ value is stored and will print in the output as shown.

Code Example:

# coding: utf-8
string = "£"
fp = open("test.txt", "w+")

fp.write("%s" % string)
print(string)

Output:

Reading the PEP that the error provides, it said the £ is not an ASCII character, despite your code’s attempts to utilize it. Use UTF-8 encoding if you can, and put # coding: utf-8 at the top of your program to get started.

To grow more complex, you may even declare encodings string by string in your code. However, you’ll need an encoder that supports it across the entire file if you’re trying to add the £ literal to your code.

You can also add the lines of code given below.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

Conclusion

Non-ASCII is not allowed in Python as the interpreter will treat it as a SyntaxError. Python can’t and shouldn’t attempt to determine what string a sequence of bytes represents outside the ASCII range.

To solve this error, you must add coding: utf-8 on the top of your program.

Понравилась статья? Поделить с друзьями:
  • Syntax error new life
  • Syntax error near unexpected token windows
  • Syntax error near unexpected token ubuntu
  • Syntax error near unexpected token python
  • Syntax error near unexpected token newline перевод