Search code examples
pythonasciinon-ascii-characters

How can I print characters like ♟ in python


I am trying to print a clean chess board in python 2.7 that uses unique characters such as ♟.

I have tried simply replacing a value in a string ("g".replace(g, ♟)) but it is changed to '\xe2\x80\xa6'. If I put the character into an online ASCII converter, it returns "226 153 159"


Solution

  • is a unicode character. In python 2, str holds ascii strings or binary data, while unicode holds unicode strings. When you do "♟" you get a binary encoded version of the unicode string. What that encoding is depends on the editor/console you used to type it in. Its common (and I think preferred) to use UTF-8 to encode strings but you may find that Windows editors favor little-endian UTF-16 strings.

    Either way, you want to write your strings as unicode as much as possible. You can do some mix-and-matching between str and unicode but make sure anything outside of the ASCII code set is unicode from the beginning.

    Python can take an encoding hint at the front of the file. So, assuming you use a UTF-8 editor, you can do

    !@/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    chess_piece = u"♟"
    print u"g".replace(u"g", chess_piece)