简体   繁体   中英

Python string indexing bug?

I ran into an interesting behavior in Python string indexing and I think might be a bug.

The purpose of my code is to perform a series of manipulation to turn a hex string into binary (12 bits) and take a subset (10 LSB) of the binary string

The code that gives the result I expect looks like this:

def test (hex):
    print (bin(int(hex,16))[2:].zfill(12)[3:12])

if input "1", ie hex = "1"

bin(int(hex,16)) returns 0b1 as expected

bin(int(hex,16))[2:] gets rid of the leading 0b and returns 1 -- works as expected [2:] give the 3rd char and onwords

bin(int(hex,16))[2:].zfill(12) returns 0000_0000_0001 ("_" added for illustration purpose)

now comes the interesting part, in order to get the 10 LSB, ie the 3rd to 12th char one would use

bin(int(hex,16))[2:].zfill(12)[2,11]

however, it seems I had to use bin(int(hex,16))[2:].zfill(12)[3,12] to get 00_0000_0001 , which seems to suggest that somehow the indexing became 1 based instead of 0 based after the .zfill(12) ?

The results is obtained with Python 3.4.1

Any suggestion is appreciated!

Here is the test code:

def test (hex):
    print (int(hex,16)) # bfn hex string to intege
    print (bin(int(hex,16))) # integer to binary string "return 0b...."
    print (bin(int(hex,16))[2:]) # get rid of the leading "0b"
    print (bin(int(hex,16))[2:].zfill(12)) # fill the string to length of 12 bits
    print (bin(int(hex,16))[2:].zfill(12)[3:12]) 

to test:

test("1")

output:

1
0b1
1
000000000001
0000000001
>>> hex = "1"
>>> bin(int(hex, 16))
'0b1'
>>> bin(int(hex, 16))[2:]
'1'
>>> bin(int(hex, 16))[2:].zfill(12)
'000000000001'
>>> bin(int(hex, 16))[2:].zfill(12)[2:]
'0000000001'
>>> bin(int(hex, 16))[2:].zfill(12)[2:11]
'000000000'

As you can see, using a slice of 2:11 as an index does not include character number 11 (the 12th character in the string). There is no bug in Python's string indexing.

If you want to index right up the the end of the string the best way to do that is to use an empty index as the second element of the slice, as I did in the second-to-last statement above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM