Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Working with UTF-8 encoding in Python source [duplicate]

Consider:

$ 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

How can I declare UTF-8 strings in source code?

Answer*

Draft saved
Draft discarded
Cancel
17
  • 8
    now it gives """UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: ordinal not in range(128)""" Commented Jun 9, 2011 at 7:36
  • 1
    You need not use unicode(), simply write string in UTF-8 encoding. Commented Jun 9, 2011 at 8:03
  • 32
    In Python versions older than 3, you also need to prefix unicode string literals with "u": some_string = u'idzie wąż wąską dróżką'. Commented Jun 9, 2011 at 8:06
  • on a diffrent string I am getting """UnicodeEncodeError: 'charmap' codec can't encode characters in position 1845-1846: character maps to <undefined>"""... does that mean a different encoding is required? Commented Jun 9, 2011 at 8:20
  • 3
    or #!/usr/bin/env python # coding: utf-8 Commented Jun 9, 2011 at 8:47

lang-py

AltStyle によって変換されたページ (->オリジナル) /