When to use utf8 as a header in py files

后端 未结 5 1563
误落风尘
误落风尘 2021-02-05 05:32

Some source files, from downloaded code, have the following header

# -*- coding: utf-8 -*-

I have an idea what utf-8 encoding is but why would

5条回答
  •  悲&欢浪女
    2021-02-05 05:54

    wherever you need to use in your code chars that aren't from ascii, like:

    ă 
    

    interpreter will complain that he doesn't understand that char.

    Usually this happens when you define constants.

    Example: Add into x.py

    print 'ă'
    

    then start a python console

    import x
    Traceback (most recent call last):
      File "", line 1, in 
      File "x.py", line 1
     SyntaxError: Non-ASCII character '\xc4' in file x.py on line 1, 
       but no encoding declared;
       see http://www.python.org/peps/pep-0263.html for details
    

提交回复
热议问题