Dmitry
Dmitry

Reputation: 7553

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?

Upvotes: 2

Views: 59

Answers (3)

user10340130
user10340130

Reputation:

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

Upvotes: 1

Dmitriy
Dmitriy

Reputation: 506

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.

Upvotes: 3

Duncan
Duncan

Reputation: 95712

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.

Upvotes: 5

Related Questions