Question

Is there a way to convert an int representing a Unicode code point to a Unicode character (string) in Python, where the same conversion code can run in both Python3+ and Python 2.7.

The resultant string is a Unicode string, either a plain string in Py3 or using 'from __future__ import unicode_literals' in pre Py3.

So we want:

i = 404
c = chr_or_unichr (i) # this code is identical for different Python versions

>>> c
'Ɣ'
Was it helpful?

Solution

How about:

try:
    chr = unichr  # Python 2
except NameError:
    pass          # Python 3

i = 404
c = chr(i) # c is now 'Ɣ' regardless of Python version

You could also create your own function name if you didn't want to overwrite Python 2's chr.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top