Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
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')


Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers


94k users

Browse Categories