8 encoding in Python source

This question already has an answer here:

  • Correct way to define Python source code encoding 5 answers

  • In source header you can declare:

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

    It is described in the PEP 0263:

    Then you can use UTF-8 in strings:

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

    This declaration is not needed in Python 3 as UTF-8 is the default source encoding (see PEP 3120).


    Additionally to above header in source code:

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

    Do not forget to verify if your text editor encodes properly your code in utf-8. Otherwise, you may have invisible characters that are not interpreted as utf-8.

    链接地址: http://www.djcxy.com/p/66362.html

    上一篇: 为什么这个程序有效? 我试图创建一个语法错误

    下一篇: 8编码在Python源代码中