在Python源代码中使用UTF-8编码

发布于 2021-02-02 23:16:36

考虑:

$ cat bla.py 
u = unicode('d…')
s = u.encode('utf-8')
print s
$ python bla.py 
  File "bla.py", line 1
SyntaxError: Non-ASCII character '\xe2' in file bla.py on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

如何在源代码中声明UTF-8字符串?

关注者
0
被浏览
96
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    在源头中,你可以声明:

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

    在PEP 0263中进行了描述:

    然后,你可以在字符串中使用UTF-8:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    u = 'idzie wąż wąską dróżką'
    uu = u.decode('utf8')
    s = uu.encode('cp1250')
    print(s)
    

    在Python 3中不需要此声明,因为UTF-8是默认的源编码(请参阅PEP 3120)。

    此外,值得验证你的文本编辑器是否已将代码正确编码为UTF-8。否则,你可能会有不被解释为UTF-8的不可见字符。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看