11

Is there a way to "insert" a Unicode character into a string in Python 3? For example,

>>>import unicode
>>>string = 'This is a full block: %s' % (unicode.charcode(U+2588))
>>>print(string)
This is a full block: █
M.J. Rayburn
  • 509
  • 4
  • 14
tkbx
  • 15,602
  • 32
  • 87
  • 122
  • 1
    Your example uses a code point, but you say "character". You should be aware that what most people mean when they say character can correspond to *several* code points. –  Nov 03 '12 at 21:58

3 Answers3

19

Yes, with unicode character escapes:

print u'This is a full block: \u2588'
Eric
  • 95,302
  • 53
  • 242
  • 374
  • 3
    … or with `unichr()`, if you want to create a character from a dynamic code point (doesn't seem to be the case here; I added it for completeness). – Sven Marnach Nov 03 '12 at 21:58
  • 2
    If you prefer something more readable, you can use `u'This is a full block: \N{FULL BLOCK}'`. – Eryk Sun Nov 03 '12 at 22:34
  • 2
    Where can I find a list of that names like `FULL BLOCK`? – buhtz Mar 23 '16 at 09:46
  • @buhtz, https://en.wikipedia.org/wiki/Block_Elements lists blocks; https://en.wikipedia.org/wiki/Unicode_symbols -> http://www.decodeunicode.org/de/u+2580 . HTH – denis Jun 03 '16 at 16:18
  • Is the number you put after the `\u` decimal, hexadecimal, octal, or what exactly? – Toothpick Anemone Oct 24 '19 at 03:57
  • @buhtz: `import unicodedata; unicodedata.name('\u2588')` also works – Eric Feb 22 '20 at 11:09
0

You can use \udddd where you replace dddd with the the charcode.

print u"Foo\u0020bar"

Prints

Foo bar
nkr
  • 3,026
  • 7
  • 31
  • 39
0

You can use \u to escape a Unicode character code:

s = u'\u0020'

which defines a string containing the space character.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490