Printing Unicode

Is it possible to write Unicode in the output, since it says:
print u’犬’
UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\u72ac’ in position 0: ordinal not in range(128)

If I try:
print u’犬’

I have just included this as an example, since it is a bit far into my experiment I would like to do so.

Kind,
Jonas.

Paste this into the very first line of your script:

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

This tells the python interpreter that it should use the UTF-8 encoding, which is capable of representing all unicode characters. If this shebang line is absent, python just assumes ascii encoding, which can’t represent your characters.

I already tried that.

The key here is that you’re wanting to print

Actually, if you’re doing this in the PsychoPy coder and it’s output panel then “no”, there’s some weird disconnect there that I can’t work out. You can read/write unicode to/from files but printing it to the output panel doesn’t work.

So the workaround is to print to a file instead.

(The reason I say this is weird is that python/psychopy can certainly print unicode to a regular terminal view, and the app is capable of writing unicode to the output view (e.g. we can add unicode to the welcome message) but somehow coming from a print statement and sending to the output window isn’t a combination that works!)

Thank you very much for your help, and the information. I will see if I can use the workaround.

Try encoding the string first, e.g.,

mystring = u'犬'
print mystring.encode('UTF-8')

or

mystring = u'犬'.encode('UTF-8')
print mystring

That seems to work. Thank you.

Dev note: redirecting stdout apparently loses the encoding. https://stackoverflow.com/questions/492483/setting-the-correct-encoding-when-piping-stdout-in-python

Thanks for solving this Jeremy. I feel sure I tried to encode in the write function of the output view, which seems like it would do the same, but maybe I should look again.

The SO post hints that we might be able to set the default encoding explicitly with sys.setdefaultencoding('utf-8')

1 Like