eri
eri

Reputation: 3524

How to make string interpreted as bytes?

Python 2 str compatable with bytes, but on Python 3 str is unicode.

I working on porting some project to Python3, but with support Python2.7. This prodject has tests with many string constants. Also there is few '...'.join(...) and '...'.format(...).

How to make Python3 to b'123' == '123' ?

Upvotes: 1

Views: 67

Answers (1)

C14L
C14L

Reputation: 12558

In Py3

>>> '123ü'.encode('utf-8')
b'123\xc3\xbc'

or

>>> bytes('123ü', 'utf-8')
b'123\xc3\xbc'

But you probably want to have it the other way around, and use UTF-8 in Py2 for easier transition. Using

# -*- coding: utf-8 -*-
from __future__ import unicode_literals`

to have all strings as u'' in Py2.

Upvotes: 3

Related Questions