欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

python2中的unicode_在python 3和2中工作的Unicode文字

发布时间:2023/12/4 48 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python2中的unicode_在python 3和2中工作的Unicode文字 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

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.

解决方案

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

总结

以上是生活随笔为你收集整理的python2中的unicode_在python 3和2中工作的Unicode文字的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。