39

So I have a python script that I'd prefer worked on python 3.2 and 2.7 just for convenience.

Is there a way to have unicode literals that work in both? E.g.

#coding: utf-8
whatever = 'שלום'

The above code would require a unicode string in python 2.x (u'') and in python 3.x that little u causes a syntax error.

2
  • @ubershmekel Which solution would you recommend? Yours or the accept answer's?
    – satoru
    Apr 19, 2013 at 2:29
  • I'd recommend using u'' since it is now supported in python 3.3 Apr 20, 2013 at 15:42

2 Answers 2

27

Edit - Since Python 3.3, the u'' literal works again, so the u() function isn't needed.

The best option is to make a method that creates unicode objects from string objects in Python 2, but leaves the string objects alone in Python 3 (as they are already unicode).

import sys
if sys.version < '3':
    import codecs
    def u(x):
        return codecs.unicode_escape_decode(x)[0]
else:
    def u(x):
        return x

You would then use it like so:

>>> print(u('\u00dcnic\u00f6de'))
Ünicöde
>>> print(u('\xdcnic\N{Latin Small Letter O with diaeresis}de'))
Ünicöde
5
  • I'd accept your answer if you removed the second part because it doesn't work for unicode literals that contain actual unescaped unicode. edit - I'd be just as happy if you clarified that nuance in the answer. Jul 15, 2011 at 6:45
  • You don't pass in unicode literals, you pass in string literals, that's the whole point of it. I tried to clarify this. Jul 15, 2011 at 9:21
  • 2
    "u() function isn't needed.", well it's needed in order to support the people who is still using Python 3.2. Oct 2, 2013 at 23:50
  • Is a 'unicode literal' not a type of 'string literal'? Feb 10, 2016 at 7:57
  • In Python 3 they are the same thing, in Python 2 they are not. Feb 12, 2016 at 21:56
0

In 3.0, 3.1, and 3.2:

from __future__ import unicode_literals

Source: ubershmekel, in the question. See revision 4 for the original.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.