简体   繁体   中英

Python: using unicode literals same way in python2 and python3

I didn't write python code for many years, so my question may be silly and simple. I load json data:

import json
data = json.loads('{"hello": "world"}')

In python 2 I should access hello key this way: data[u'hello'] . There is an additional u symbol because keys are Unicode.

In python 3: data['hello'] . Unicode strings by default.

What should I do if I want to write portable code?

As long as you are using Python 3.3 or later you can use the unicode prefix on strings. That will allow you to write code that runs without change on both Python 2 and Python 3.3+.

See https://www.python.org/dev/peps/pep-0414/

Alternatively you code do from __future__ import unicode_literals at the top of your code and then all strings default to unicode literals and you would have to use the b"" prefix in front of byte strings even in Python2.

Add this to the top of your file

# -*- coding: utf-8 -*-

from __future__ import unicode_literals

This is still not exactly the same as in python3 but helps you to make it portable. If you are willing to support it for both 2 and 3, you have to look at six module as well to handle generators/iterators, strings differences.

data[u'hello']在python 2和3中都有效。但是data.get('hello')更好。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM