Issue
Is there any simple way to get consistent results in both Python 2 and Python 3 for operatioIn like "give me N-th byte in byte string"? Getting either byte-as-integer or byte-as-character will do for me, as long as that will be consistent.
I.e. given
s = b"123"
Naïve approach yields:
s[1] # => Python 2: '2', <type 'str'>
s[1] # => Python 3: 50, <class 'int'>
Wrapping that in ord(...)
yields an error in Python 3:
ord(s[1]) # => Python 2: 50, <type 'int'>
ord(s[1]) # => Python 3: TypeError: ord() expected string of length 1, but int found
I can think of a fairly complicated compat solution:
ord(s[1]) if (type(s[1]) == type("str")) else s[1] # 50 in both Python 2 and 3
... but may be there's an easier way which I just don't notice?
Solution
A length-1 slice will be also be a byte-sequence in either 2.x or 3.x:
s = b'123'
s[1:2] # 3.x: b'2'; 2.x: '2', which is the same thing but the repr() rules are different.
Answered By - Karl Knechtel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.