Running Python 2.7 Code With Unicode Characters in Source

Viewed 2726

I want to run a Python source file that contains unicode (utf-8) characters in the source. I am aware of the fact that this can be done by adding the comment # -*- coding: utf-8 -*- in the beginning. However, I wish to do it without using this method.

One way I could think of was writing the unicode strings in escaped form. For example,

Edit: Updated Source. Added Unicode comments.

# Printing naïve and 男孩
def fxn():
    print 'naïve'
    print '男孩'
fxn()

becomes

# Printing na\xc3\xafve and \xe7\x94\xb7\xe5\xad\xa9
def fxn():
    print 'na\xc3\xafve'
    print '\xe7\x94\xb7\xe5\xad\xa9'
fxn()

I have two questions regarding the above method.

  1. How do I convert the first code snippet, using Python, into its equivalent that follows it? That is, only unicode sequences should be written in escaped form.
  2. Is the method foolproof considering only unicode (utf-8) characters are used? Is there something that can go wrong?
5 Answers
Related