How to Handle UTF-8 Encoding in Python Source Code?

Mary-Kate Olsen
Release: 2024-10-29 00:39:30
Original
446 people have browsed it

How to Handle UTF-8 Encoding in Python Source Code?

Addressing UTF-8 Encoding in Python Source Code

Issue

When attempting to encode UTF-8 characters in Python 2 source code, the following error may occur due to the lack of an explicitly declared encoding:

SyntaxError: Non-ASCII character '\xe2' in file bla.py on line 1, but no encoding declared
Copy after login

Resolution

Python 3:

UTF-8 is the default encoding in Python 3, allowing for the seamless use of Unicode characters anywhere in the source code.

Python 2:

In Python 2, the following header can be included at the beginning of the source file to declare UTF-8 encoding:

# -*- coding: utf-8 -*-
Copy after login

This adheres to the guidelines outlined in PEP 0263. Once declared, UTF-8 can be utilized in strings as follows:

<code class="python"># -*- coding: utf-8 -*-

u = 'idzie wąż wąską dróżką'
uu = u.decode('utf8')
s = uu.encode('cp1250')
print(s)</code>
Copy after login

The above is the detailed content of How to Handle UTF-8 Encoding in Python Source Code?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!