Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (19k points)


$ cat

u = unicode('d…')

s = u.encode('utf-8')

print s

$ python

File "", line 1

SyntaxError: Non-ASCII character '\xe2' in file on line 1, but no encoding declared; see for details

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

1 Answer

0 votes
by (106k points)

If you are working with Python 3 this declaration is not needed as UTF-8 is the default source encoding. One important point to note here, you should verify that your text editor properly encodes your code in UTF-8. Otherwise, you may have invisible characters that are not interpreted as UTF-8.

Before writing the code you should declare the source header at the start.

#!/usr/bin/env python

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

Below is the code that illustrates the use of  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')


Browse Categories