Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

Unicode literals that work in python 3 and 2

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.

question from:https://stackoverflow.com/questions/6625782/unicode-literals-that-work-in-python-3-and-2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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('u00dcnicu00f6de'))
ünic?de
>>> print(u('xdcnicN{Latin Small Letter O with diaeresis}de'))
ünic?de

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...