9

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

>>>import unicode
>>>string = u'This is a full block: %s' % (unicode.charcode(U+2588))
>>>print string
This is a full block: █
tkbx
  • 14,366
  • 27
  • 82
  • 118
  • 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

17

Yes, with unicode character escapes:

print u'This is a full block: \u2588'
Eric
  • 91,378
  • 50
  • 226
  • 356
  • 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
  • 1
    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
  • 2,987
  • 7
  • 30
  • 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
  • 587,191
  • 41
  • 1,025
  • 1,442