2

I am trying to print the Unicode Bitcoin symbol \u2043 in Python 2. I have tried adding #-*- coding: utf-8 -*-.

$ python2 -c 'print u'\u0243''

Raises UnicodeEncodeError: 'ascii' codec can't encode character u'\u0243' in position 0: ordinal not in range(128). However, doing this from the Python shell works.

$ python2
>>> print u'\u0243'
Ƀ

Why isn't this code working?

bitcoin = u'\u0243'
quote = u'{:,.2f}'.format(float(val), '.2f')
print bitcoin, quote
davidism
  • 121,510
  • 29
  • 395
  • 339
  • 1
    The error message is telling you that your terminal encoding is ascii, and that `\u0243` can't be encoded to ascii. Perhaps setting the `PYTHONIOENCODING` environment variable to e.g. `utf-8` would help.. – thebjorn Oct 10 '15 at 13:18
  • I am using Konsole in KDE, and rightl clicking on it I can see the UTF-8 selected when looking at the Encoding. Is this more of a bash issue? http://joelhy.github.io/img/konsole_select_encoding.jpg – Alexandro Colorado Oct 10 '15 at 13:21
  • Sorry, I don't know.. I'm on windows, and there unicode and the console has never been friends.. – thebjorn Oct 10 '15 at 13:23
  • Thanks @thebjorn that worked. I thought I had that setup but missread the envvar to PYTHONENCODING instead of PYTHON**IO**ENCODING. – Alexandro Colorado Oct 10 '15 at 13:28
  • It also worked by adding bitcoin= u'u\0243'.encoding('utf-8') at the end of the variable. – Alexandro Colorado Oct 11 '15 at 00:05
  • Unicode added the standard Bitcoin symbol ₿ in 2017 as U+20BF; in Python it is \u20bf – Ken Shirriff Oct 10 '17 at 20:44

1 Answers1

1

On Unix, if sys.stdout.isatty() returns True but sys.stdout.encoding is 'ANSI_X3.4-1968' (ascii) then you should configure your locale (check LANG, LC_CTYPE, LC_ALL envvars) to use non-ascii encoding if you need to print non-ascii characters.

If sys.stdout.isatty() is false then configure PYTHONIOENCODING envvar outside your script.
Always print Unicode, don't hardcode the character encoding of your environment inside your script.

jfs
  • 399,953
  • 195
  • 994
  • 1,670