Issue
I'm experimenting with bytes
vs bytearray
in Python 2.6. I don't understand the reason for some differences.
A bytes
iterator returns strings:
for i in bytes(b"hi"):
print(type(i))
Gives:
<type 'str'>
<type 'str'>
But a bytearray
iterator returns int
s:
for i in bytearray(b"hi"):
print(type(i))
Gives:
<type 'int'>
<type 'int'>
Why the difference?
I'd like to write code that will translate well into Python 3. So, is the situation the same in Python 3?
Solution
In Python 2.6 bytes is merely an alias for str.
This "pseudo type" was introduced to [partially] prepare programs [and programmers!] to be converted/compatible with Python 3.0 where there is a strict distinction of semantics and use for str (which are systematically unicode) and bytes (which are arrays of octets, for storing data, but not text)
Similarly the b prefix for string literals is ineffective in 2.6, but it is a useful marker in the program, which flags explicitly the intent of the programmer to have the string as a data string rather than a text string. This info can then be used by the 2to3 converter or similar utilities when the program is ported to Py3k.
You may want to check this SO Question for additional info.
Answered By - mjv
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.