[Tutor] string replacement in Python 2 and 3
Albert-Jan Roskam
fomcl at yahoo.com
Tue Nov 26 20:42:29 CET 2013
Hi,
String replacement works quite differently with bytes objects in Python 3 than with string objects in Python 2. What is the best way to make example #1 below run in Python 2 and 3? Should one really decode the bytes keys and (if applicable) the values to unicode? The code gets so bloated with all these decodes all over the place. But to avoid ugly things like under #2 (Python 3) I see no other option, same for the errors of the other examples. Or am I overlooking something? I guess I am treating python 2 strings too much like python 3 bytes.
#Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
>>> kwargs = {b'a': 1, b'b': 2} # 1
>>> b'%(a)s, %(b)s' % kwargs
'1, 2'
>>> '%s' % b'ugly' # 2
'ugly'
>>> b'%s' % b'ugly' # 3
'ugly'
>>> b'%s'.decode('utf-8') % 'ugly' #4
u'ugly'
# Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (Intel)] on win32
>>> kwargs = {b'a': 1, b'b': 2} # 1
>>> b'%(a)s, %(b)s' % kwargs
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
b'%(a)s, %(b)s' % kwargs
TypeError: unsupported operand type(s) for %: 'bytes' and 'dict'
>>> '%s' % b'ugly' # 2
"b'ugly'"
>>> b'%s' % b'ugly' # 3
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
b'%s' % b'ugly'
TypeError: unsupported operand type(s) for %: 'bytes' and 'bytes'
>>> b'%s' % 'ugly' # 4
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
b'%s' % 'ugly'
TypeError: unsupported operand type(s) for %: 'bytes' and 'str'
>>> b'%s'.decode('utf-8') % 'ugly'
'ugly'
Regards,
Albert-Jan
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a
fresh water system, and public health, what have the Romans ever done for us?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
More information about the Tutor
mailing list