2

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?

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

data[u'hello'] works in both python 2 and 3. But data.get('hello') is even better.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.